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

version 1.326, 2009/01/28 11:51:22 version 1.418, 2010/02/02 01:28:10
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)$/) {          $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
     if ($url =~ m{/res/}) {   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
  # no copy for published maps      $name.': <br />'.$foldertitle;
  $nocopy = 1;      }
     } else {      if (wantarray) {
  foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {   return ($title,$foldertitle,$renametitle);
     my ($title,$url,$ext,$type)=split(/\:/,$item);      }
     if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {      return $title;
  $nocopy=1;  }
  last;  
     }  # --------------------------------------------------------------- An entry line
  }  
     }  sub entryline {
  }      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum,$crstype)=@_;
         if ($url=~/^\/res\/lib\/templates\//) {      my ($foldertitle,$pagetitle,$renametitle);
            $nocopy=1;      if (&is_supplemental_title($title)) {
            $nocut=1;   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
         }   $pagetitle = $foldertitle;
         my $copylink='&nbsp;';      } else {
         my $cutlink='&nbsp;';   $title=&HTML::Entities::encode($title,'"<>&\'');
    $renametitle=$title;
  my $skip_confirm = 0;   $foldertitle=$title;
  if ( $folder =~ /^supplemental/   $pagetitle=$title;
      || ($url =~ m{( /smppg$      }
     |/syllabus$  
     |/aboutme$      my $orderidx=$LONCAPA::map::order[$index];
     |/navmaps$  
     |/bulletinboard$  
     |\.html$      $renametitle=~s/\\/\\\\/g;
     |^/adm/wrapper/ext)}x)) {      $renametitle=~s/\&quot\;/\\\"/g;
     $skip_confirm = 1;      $renametitle=~s/ /%20/g;
  }      my $line=&Apache::loncommon::start_data_table_row();
       my ($form_start,$form_end);
  if (!$nocopy) {  # Edit commands
     $copylink=(<<ENDCOPY);      my ($container, $type, $esc_path, $path, $symb);
 <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>      if ($env{'form.folderpath'}) {
 ENDCOPY   $type = 'folder';
         }          $container = 'sequence';
  if (!$nocut) {   $esc_path=&escape($env{'form.folderpath'});
     $cutlink=(<<ENDCUT);   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 ENDCUT      }
         }      if ($env{'form.pagepath'}) {
  $form_start = (<<END);          $type = $container = 'page';
    <form  action="/adm/coursedocs" method="post">          $esc_path=&escape($path = $env{'form.pagepath'});
    <input type="hidden" name="${type}path" value="$path" />   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
    <input type="hidden" name="${type}symb" value="$symb" />          $symb=&escape($env{'form.pagesymb'});
    <input type="hidden" name="setparms" value="$orderidx" />      }
    <input type="hidden" name="changeparms" value="0" />      my $cpinfo='';
 END      if ($allowed) {
         $form_end = '</form>';   my $incindex=$index+1;
  $line.=(<<END);   my $selectbox='';
 <td>   if (($folder!~/^supplemental/) &&
    <table class="LC_docs_entry_move">      ($#LONCAPA::map::order>0) &&
       <tr>      ((split(/\:/,
          <td>       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
             <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>       ne '') &&
          </td>      ((split(/\:/,
       </tr>       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
       <tr>       ne '')) {
         <td>      $selectbox=
            <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>   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
         </td>   '<select name="newpos" onchange="this.form.submit()">';
       </tr>      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
     </table>   if ($i==$incindex) {
 </td>      $selectbox.='<option value="" selected="selected">('.$i.')</option>';
 <td>   } else {
    $form_start      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
    $selectbox   }
    $form_end      }
 </td>      $selectbox.='</select>';
 <td class="LC_docs_entry_commands">   }
    <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>   my %lt=&Apache::lonlocal::texthash(
 $cutlink                  'up' => 'Move Up',
    <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>   'dw' => 'Move Down',
 $copylink   'rm' => 'Remove',
 </td>                  'ct' => 'Cut',
 END   'rn' => 'Rename',
    'cp' => 'Copy');
     }   my $nocopy=0;
 # Figure out what kind of a resource this is          my $nocut=0;
     my ($extension)=($url=~/\.(\w+)$/);          if ($url=~/\.(page|sequence)$/) {
     my $uploaded=($url=~/^\/*uploaded\//);      if ($url =~ m{/res/}) {
     my $icon=&Apache::loncommon::icon($url);   # no copy for published maps
     my $isfolder=0;   $nocopy = 1;
     my $ispage=0;      } else {
     my $folderarg;   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
     my $pagearg;      my ($title,$url,$ext,$type)=split(/\:/,$item);
     my $pagefile;      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
     if ($uploaded) {   $nocopy=1;
  if ($extension eq 'sequence') {   last;
     $icon=$iconpath.'/folder_closed.gif';      }
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;   }
     $url='/adm/coursedocs?';      }
     $folderarg=$1;   }
     $isfolder=1;          if ($url=~/^\/res\/lib\/templates\//) {
         } elsif ($extension eq 'page') {             $nocopy=1;
             $icon=$iconpath.'/page.gif';             $nocut=1;
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;          }
             $pagearg=$1;          my $copylink='&nbsp;';
             $url='/adm/coursedocs?';          my $cutlink='&nbsp;';
             $ispage=1;  
  } else {   my $skip_confirm = 0;
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);   if ( $folder =~ /^supplemental/
  }       || ($url =~ m{( /smppg$
     }      |/syllabus$
          |/aboutme$
     my $orig_url = $url;      |/navmaps$
     my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});      |/bulletinboard$
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {      |\.html$
  my $symb=&Apache::lonnet::symbclean(      |^/adm/wrapper/ext)}x)) {
           &Apache::lonnet::declutter('uploaded/'.      $skip_confirm = 1;
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   }
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.  
            '.sequence').   if (!$nocopy) {
            '___'.$residx.'___'.      $copylink=(<<ENDCOPY);
    &Apache::lonnet::declutter($url));  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);  ENDCOPY
  $url=&Apache::lonnet::clutter($url);          }
  if ($url=~/^\/*uploaded\//) {   if (!$nocut) {
     $url=~/\.(\w+)$/;      $cutlink=(<<ENDCUT);
     my $embstyle=&Apache::loncommon::fileembstyle($1);  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {  ENDCUT
  $url='/adm/wrapper'.$url;          }
     } elsif ($embstyle eq 'ssi') {   $form_start = (<<END);
  #do nothing with these     <form  action="/adm/coursedocs" method="post">
     } elsif ($url!~/\.(sequence|page)$/) {     <input type="hidden" name="${type}path" value="$path" />
  $url='/adm/coursedocs/showdoc'.$url;     <input type="hidden" name="${type}symb" value="$symb" />
     }     <input type="hidden" name="setparms" value="$orderidx" />
  } elsif ($url=~m|^/ext/|) {     <input type="hidden" name="changeparms" value="0" />
     $url='/adm/wrapper'.$url;  END
     $external = 1;          $form_end = '</form>';
  }   $line.=(<<END);
         if (&Apache::lonnet::symbverify($symb,$url)) {  <td>
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);  <div class="LC_docs_entry_move">
         } else {    <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'>
             $url='';      <img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" />
         }    </a>
  if ($container eq 'page') {  </div>
     my $symb=$env{'form.pagesymb'};  <div class="LC_docs_entry_move">
             <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'>
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);      <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" />
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);    </a>
  }  </div>
     }  </td>
     my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');  <td>
     if ($isfolder || $extension eq 'sequence') {     $form_start
  my $foldername=&escape($foldertitle);     $selectbox
  my $folderpath=$env{'form.folderpath'};     $form_end
  if ($folderpath) { $folderpath.='&' };  </td>
 # Append randompick number, hidden, and encrypted with ":" to foldername,  <td class="LC_docs_entry_commands">
 # so it gets transferred between levels     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,  $cutlink
                                               'parameter_randompick'))[0]     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
                                                .':'.((&LONCAPA::map::getparameter($orderidx,  $copylink
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)  </td>
                                                .':'.((&LONCAPA::map::getparameter($orderidx,  END
                                               'parameter_encrypturl'))[0]=~/^yes$/i)  
                                                .':'.((&LONCAPA::map::getparameter($orderidx,      }
                                               'parameter_randomorder'))[0]=~/^yes$/i);  # Figure out what kind of a resource this is
  $url.='folderpath='.&escape($folderpath).$cpinfo;      my ($extension)=($url=~/\.(\w+)$/);
  $parameterset='<label>'.&mt('Randomly Pick: ').      my $uploaded=($url=~/^\/*uploaded\//);
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.      my $icon=&Apache::loncommon::icon($url);
     (&LONCAPA::map::getparameter($orderidx,      my $isfolder=0;
                                               'parameter_randompick'))[0].      my $ispage=0;
                                               '" />'.      my $folderarg;
 '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';      my $pagearg;
     my $ro_set=      my $pagefile;
     ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');      if ($uploaded) {
  $rand_order_text ='   if ($extension eq 'sequence') {
 <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>';        $icon=$iconpath.'/navmap.folder.closed.gif';
     }      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
     if ($ispage) {      $url='/adm/coursedocs?';
         my $pagename=&escape($pagetitle);      $folderarg=$1;
         my $pagepath;      $isfolder=1;
         my $folderpath=$env{'form.folderpath'};          } elsif ($extension eq 'page') {
         if ($folderpath) { $pagepath = $folderpath.'&' };              $icon=$iconpath.'/page.gif';
         $pagepath.=$pagearg.'&'.$pagename;              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
  my $symb=$env{'form.pagesymb'};              $pagearg=$1;
  if (!$symb) {              $url='/adm/coursedocs?';
     my $path='uploaded/'.              $ispage=1;
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   } else {
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',   }
        $residx,      }
        $path.$pagearg.'.page');  
  }      my $orig_url = $url;
  $url.='pagepath='.&escape($pagepath).      $orig_url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
     '&amp;pagesymb='.&escape($symb).$cpinfo;      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
     }      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
     if ($external) {   my $symb=&Apache::lonnet::symbclean(
  my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';            &Apache::lonnet::declutter('uploaded/'.
  $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'}.'.domain'}.'/'.
     } else {             $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
  undef($external);             '.sequence').
     }             '___'.$residx.'___'.
     $line.='     &Apache::lonnet::declutter($url));
   <td class="LC_docs_entry_icon">   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'   $url=&Apache::lonnet::clutter($url);
   </td>   if ($url=~/^\/*uploaded\//) {
   <td class="LC_docs_entry_title">      $url=~/\.(\w+)$/;
     '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."      my $embstyle=&Apache::loncommon::fileembstyle($1);
   </td>";      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
     if (($allowed) && ($folder!~/^supplemental/)) {   $url='/adm/wrapper'.$url;
   my %lt=&Apache::lonlocal::texthash(      } elsif ($embstyle eq 'ssi') {
        'hd' => 'Hidden',   #do nothing with these
        'ec' => 'URL hidden');      } elsif ($url!~/\.(sequence|page)$/) {
  my $enctext=   $url='/adm/coursedocs/showdoc'.$url;
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');      }
  my $hidtext=   } elsif ($url=~m|^/ext/|) {
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');      $url='/adm/wrapper'.$url;
  $line.=(<<ENDPARMS);      $external = 1;
   <td class="LC_docs_entry_parameter">   }
     $form_start          if (&Apache::lonnet::symbverify($symb,$url)) {
     <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
     $form_end          } else {
   </td>              $url='';
   <td class="LC_docs_entry_parameter">          }
     $form_start   if ($container eq 'page') {
     <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>      my $symb=$env{'form.pagesymb'};
     $form_end  
   </td>      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
   <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
   <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>   }
 ENDPARMS      }
     }      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
     $line.="</tr>";      if ($isfolder || $extension eq 'sequence') {
     return $line;   my $foldername=&escape($foldertitle);
 }   my $folderpath=$env{'form.folderpath'};
    if ($folderpath) { $folderpath.='&' };
 =pod  # Append randompick number, hidden, and encrypted with ":" to foldername,
   # so it gets transferred between levels
 =item tiehash()   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_randompick'))[0]
 tie the hash                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_hiddenresource'))[0]=~/^yes$/i)
 =cut                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_encrypturl'))[0]=~/^yes$/i)
 sub tiehash {                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     my ($mode)=@_;                                                'parameter_randomorder'))[0]=~/^yes$/i);
     $hashtied=0;   $url.='folderpath='.&escape($folderpath).$cpinfo;
     if ($env{'request.course.fn'}) {   $parameterset='<label>'.&mt('Randomly Pick: ').
  if ($mode eq 'write') {      '<input type="text" size="4" onchange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      (&LONCAPA::map::getparameter($orderidx,
     &GDBM_WRCREAT(),0640)) {                                                'parameter_randompick'))[0].
                 $hashtied=2;                                                '" />'.
     }  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
  } else {      my $ro_set=
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
     &GDBM_READER(),0640)) {   $rand_order_text ='
                 $hashtied=1;  <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>';
     }      }
  }      if ($ispage) {
     }              my $pagename=&escape($pagetitle);
 }          my $pagepath;
           my $folderpath=$env{'form.folderpath'};
 sub untiehash {          if ($folderpath) { $pagepath = $folderpath.'&' };
     if ($hashtied) { untie %hash; }          $pagepath.=$pagearg.'&'.$pagename;
     $hashtied=0;   my $symb=$env{'form.pagesymb'};
     return OK;   if (!$symb) {
 }      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,
 sub checkonthis {         $path.$pagearg.'.page');
     my ($r,$url,$level,$title)=@_;   }
     $url=&unescape($url);   $url.='pagepath='.&escape($pagepath).
     $alreadyseen{$url}=1;      '&amp;pagesymb='.&escape($symb).$cpinfo;
     $r->rflush();      }
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {      if (($external) && ($allowed)) {
        $r->print("\n<br />");   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
        if ($level==0) {   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
            $r->print("<br />");      } else {
        }   undef($external);
        for (my $i=0;$i<=$level*5;$i++) {      }
            $r->print('&nbsp;');      my $reinit;
        }      if ($crstype eq 'Community') {
        $r->print('<a href="'.$url.'" target="cat">'.          $reinit = &mt('(re-initialize community to access)');
  ($title?$title:$url).'</a> ');      } else {
        if ($url=~/^\/res\//) {          $reinit = &mt('(re-initialize course to access)');
   my $result=&Apache::lonnet::repcopy(      }  
                               &Apache::lonnet::filelocation('',$url));      $line.='
           if ($result eq 'ok') {    <td>
              $r->print('<span class="LC_success">'.&mt('ok').'</span>');      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
              $r->rflush();    </td>
              &Apache::lonnet::countacc($url);    <td>
              $url=~/\.(\w+)$/;      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.$reinit.'</span>').$external."
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {    </td>";
  $r->print('<br />');      if (($allowed) && ($folder!~/^supplemental/)) {
                  $r->rflush();    my %lt=&Apache::lonlocal::texthash(
                  for (my $i=0;$i<=$level*5;$i++) {         'hd' => 'Hidden',
                      $r->print('&nbsp;');         'ec' => 'URL hidden');
                  }   my $enctext=
                  $r->print('- '.&mt('Rendering:').' ');      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="checked"':'');
  my ($errorcount,$warningcount)=split(/:/,   my $hidtext=
        &Apache::lonnet::ssi_body($url,      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="checked"':'');
        ('grade_target'=>'web',   $line.=(<<ENDPARMS);
  'return_only_error_and_warning_counts' => 1)));    <td class="LC_docs_entry_parameter">
                  if (($errorcount) ||      $form_start
                      ($warningcount)) {      <label><input type="checkbox" name="hiddenresource_$orderidx" onclick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
      if ($errorcount) {      $form_end
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.    </td>
                           &mt('[quant,_1,error]',$errorcount).'</span>');    <td class="LC_docs_entry_parameter">
                      }      $form_start
      if ($warningcount) {      <label><input type="checkbox" name="encrypturl_$orderidx" onclick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
                         $r->print('<span class="LC_warning">'.      $form_end
                           &mt('[quant,_1,warning]',$warningcount).'</span>');    </td>
                      }    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
                  } else {    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
                      $r->print('<span class="LC_success">'.&mt('ok').'</span>');  ENDPARMS
                  }      }
                  $r->rflush();      $line.=&Apache::loncommon::end_data_table_row();
              }      return $line;
      my $dependencies=  }
                 &Apache::lonnet::metadata($url,'dependencies');  
              foreach my $dep (split(/\,/,$dependencies)) {  =pod
  if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {  
                     &checkonthis($r,$dep,$level+1);  =item tiehash()
                  }  
              }  tie the hash
           } elsif ($result eq 'unavailable') {  
              $r->print('<span class="LC_error">'.&mt('connection down').'</span>');  =cut
           } elsif ($result eq 'not_found') {  
       unless ($url=~/\$/) {  sub tiehash {
   $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');      my ($mode)=@_;
       } else {      $hashtied=0;
   $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');      if ($env{'request.course.fn'}) {
       }   if ($mode eq 'write') {
           } else {      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
              $r->print('<span class="LC_error">'.&mt('access denied').'</span>');      &GDBM_WRCREAT(),0640)) {
           }                  $hashtied=2;
        }      }
     }   } else {
 }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
       &GDBM_READER(),0640)) {
                   $hashtied=1;
       }
 =pod   }
       }
 =item list_symbs()  }
   
 List Symbs  sub untiehash {
       if ($hashtied) { untie %hash; }
 =cut      $hashtied=0;
       return OK;
 sub list_symbs {  }
     my ($r) = @_;  
   
     my $type = &Apache::loncommon::course_type();  
     $r->print(&Apache::loncommon::start_page('Symb List'));  
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));  sub checkonthis {
     my $navmap = Apache::lonnavmaps::navmap->new();      my ($r,$url,$level,$title)=@_;
     if (!defined($navmap)) {      $url=&unescape($url);
         $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.      $alreadyseen{$url}=1;
                   '<div class="LC_error">'.      $r->rflush();
                   &mt('Unable to retrieve information about course contents').      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
                   '</div>');         $r->print("\n<br />");
         &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});         if ($level==0) {
     } else {             $r->print("<br />");
         $r->print("<pre>\n");         }
         foreach my $res ($navmap->retrieveResources()) {         for (my $i=0;$i<=$level*5;$i++) {
     $r->print($res->compTitle()."\t".$res->symb()."\n");             $r->print('&nbsp;');
         }         }
         $r->print("\n</pre>\n");         $r->print('<a href="'.$url.'" target="cat">'.
     }   ($title?$title:$url).'</a> ');
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');         if ($url=~/^\/res\//) {
 }    my $result=&Apache::lonnet::repcopy(
                                 &Apache::lonnet::filelocation('',$url));
             if ($result eq 'ok') {
 sub verifycontent {               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     my ($r) = @_;               $r->rflush();
     my $type = &Apache::loncommon::course_type();               &Apache::lonnet::countacc($url);
    my $loaderror=&Apache::lonnet::overloaderror($r);               $url=~/\.(\w+)$/;
    if ($loaderror) { return $loaderror; }               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));   $r->print('<br />');
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));                   $r->rflush();
    $hashtied=0;                   for (my $i=0;$i<=$level*5;$i++) {
    undef %alreadyseen;                       $r->print('&nbsp;');
    %alreadyseen=();                   }
    &tiehash();                   $r->print('- '.&mt('Rendering:').' ');
    foreach my $key (keys(%hash)) {   my ($errorcount,$warningcount)=split(/:/,
        if ($hash{$key}=~/\.(page|sequence)$/) {         &Apache::lonnet::ssi_body($url,
    if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {         ('grade_target'=>'web',
        $r->print('<hr /><span class="LC_error">'.   'return_only_error_and_warning_counts' => 1)));
  &mt('The following sequence or page is included more than once in your '.$type.': ').                   if (($errorcount) ||
  &unescape($hash{$key}).'</span><br />'.                       ($warningcount)) {
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));       if ($errorcount) {
    }                          $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})})) {                       }
            &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});       if ($warningcount) {
        }                          $r->print('<span class="LC_warning">'.
    }                            &mt('[quant,_1,warning]',$warningcount).'</span>');
    &untiehash();                       }
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.                   } else {
      &mt('Return to DOCS').'</a>');                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
 }                   }
                    $r->rflush();
                }
 sub devalidateversioncache {       my $dependencies=
     my $src=shift;                  &Apache::lonnet::metadata($url,'dependencies');
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.               foreach my $dep (split(/\,/,$dependencies)) {
   &Apache::lonnet::clutter($src));   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
 }                      &checkonthis($r,$dep,$level+1);
                    }
 sub checkversions {               }
     my ($r) = @_;            } elsif ($result eq 'unavailable') {
     my $type = &Apache::loncommon::course_type();               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));            } elsif ($result eq 'not_found') {
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));        unless ($url=~/\$/) {
     my $header='';    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
     my $startsel='';        } else {
     my $monthsel='';    $r->print('<span class="LC_error">'.&mt('unable to verify variable URL').'</span>');
     my $weeksel='';        }
     my $daysel='';            } else {
     my $allsel='';               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     my %changes=();            }
     my $starttime=0;         }
     my $haschanged=0;      }
     my %setversions=&Apache::lonnet::dump('resourceversions',  }
   $env{'course.'.$env{'request.course.id'}.'.domain'},  
   $env{'course.'.$env{'request.course.id'}.'.num'});  
   
     $hashtied=0;  =pod
     &tiehash();  
     my %newsetversions=();  =item list_symbs()
     if ($env{'form.setmostrecent'}) {  
  $haschanged=1;  List Symbs
  foreach my $key (keys(%hash)) {  
     if ($key=~/^ids\_(\/res\/.+)$/) {  =cut
  $newsetversions{$1}='mostrecent';  
                 &devalidateversioncache($1);  sub list_symbs {
     }      my ($r) = @_;
  }  
     } elsif ($env{'form.setcurrent'}) {      my $crstype = &Apache::loncommon::course_type();
  $haschanged=1;      $r->print(&Apache::loncommon::start_page('Symb List'));
  foreach my $key (keys(%hash)) {      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
     if ($key=~/^ids\_(\/res\/.+)$/) {      my $navmap = Apache::lonnavmaps::navmap->new();
  my $getvers=&Apache::lonnet::getversion($1);      if (!defined($navmap)) {
  if ($getvers>0) {          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
     $newsetversions{$1}=$getvers;                    '<div class="LC_error">'.
     &devalidateversioncache($1);                    &mt('Unable to retrieve information about course contents').
  }                    '</div>');
     }          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
  }      } else {
     } elsif ($env{'form.setversions'}) {          $r->print("<pre>\n");
  $haschanged=1;          foreach my $res ($navmap->retrieveResources()) {
  foreach my $key (keys(%env)) {      $r->print($res->compTitle()."\t".$res->symb()."\n");
     if ($key=~/^form\.set_version_(.+)$/) {          }
  my $src=$1;          $r->print("\n</pre>\n");
  if (($env{$key}) && ($env{$key} ne $setversions{$src})) {      }
     $newsetversions{$src}=$env{$key};      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
     &devalidateversioncache($src);  }
  }  
     }  
  }  sub verifycontent {
     }      my ($r) = @_;
     if ($haschanged) {      my $crstype = &Apache::loncommon::course_type();
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,     my $loaderror=&Apache::lonnet::overloaderror($r);
   $env{'course.'.$env{'request.course.id'}.'.domain'},     if ($loaderror) { return $loaderror; }
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {     $r->print(&Apache::loncommon::start_page('Verify '.$crstype.' Documents'));
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$crstype.' Documents'));
  } else {     $hashtied=0;
     $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');     undef %alreadyseen;
  }     %alreadyseen=();
  &mark_hash_old();     &tiehash();
     }     foreach my $key (keys(%hash)) {
     &changewarning($r,'');         if ($hash{$key}=~/\.(page|sequence)$/) {
     if ($env{'form.timerange'} eq 'all') {     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
 # show all documents         $r->print('<hr /><span class="LC_error">'.
  $header=&mt('All Documents in '.$type);   &mt('The following sequence or page is included more than once in your '.$crstype.': ').
  $allsel=1;   &unescape($hash{$key}).'</span><br />'.
  foreach my $key (keys(%hash)) {   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
     if ($key=~/^ids\_(\/res\/.+)$/) {     }
  my $src=$1;         }
  $changes{$src}=1;         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
     }             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
  }         }
     } else {     }
 # show documents which changed     &untiehash();
  %changes=&Apache::lonnet::dump     $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},       &mt('Return to DOCS').'</a>');
                      $env{'course.'.$env{'request.course.id'}.'.num'});  }
  my $firstkey=(keys(%changes))[0];  
  unless ($firstkey=~/^error\:/) {  
     unless ($env{'form.timerange'}) {  sub devalidateversioncache {
  $env{'form.timerange'}=604800;      my $src=shift;
     }      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '    &Apache::lonnet::clutter($src));
  .&mt('seconds');  }
     if ($env{'form.timerange'}==-1) {  
  $seltext='since start of course';  sub checkversions {
  $startsel='selected';      my ($r) = @_;
  $env{'form.timerange'}=time;      my $crstype = &Apache::loncommon::course_type();
     }      $r->print(&Apache::loncommon::start_page("Check $crstype Document Versions"));
     $starttime=time-$env{'form.timerange'};      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $crstype Document Versions"));
     if ($env{'form.timerange'}==2592000) {      my $header='';
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      my $startsel='';
  $monthsel='selected';      my $monthsel='';
     } elsif ($env{'form.timerange'}==604800) {      my $weeksel='';
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      my $daysel='';
  $weeksel='selected';      my $allsel='';
     } elsif ($env{'form.timerange'}==86400) {      my %changes=();
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';      my $starttime=0;
  $daysel='selected';      my $haschanged=0;
     }      my %setversions=&Apache::lonnet::dump('resourceversions',
     $header=&mt('Content changed').' '.$seltext;    $env{'course.'.$env{'request.course.id'}.'.domain'},
  } else {    $env{'course.'.$env{'request.course.id'}.'.num'});
     $header=&mt('No content modifications yet.');  
  }      $hashtied=0;
     }      &tiehash();
     %setversions=&Apache::lonnet::dump('resourceversions',      my %newsetversions=();
   $env{'course.'.$env{'request.course.id'}.'.domain'},      if ($env{'form.setmostrecent'}) {
   $env{'course.'.$env{'request.course.id'}.'.num'});   $haschanged=1;
     my %lt=&Apache::lonlocal::texthash   foreach my $key (keys(%hash)) {
       ('st' => 'Version changes since start of '.$type,      if ($key=~/^ids\_(\/res\/.+)$/) {
        'lm' => 'Version changes since last Month',   $newsetversions{$1}='mostrecent';
        'lw' => 'Version changes since last Week',                  &devalidateversioncache($1);
        'sy' => 'Version changes since Yesterday',      }
                'al' => 'All Resources (possibly large output)',   }
        'sd' => 'Display',      } elsif ($env{'form.setcurrent'}) {
        'fi' => 'File',   $haschanged=1;
        'md' => 'Modification Date',   foreach my $key (keys(%hash)) {
                'mr' => 'Most recently published Version',      if ($key=~/^ids\_(\/res\/.+)$/) {
        've' => 'Version used in '.$type,   my $getvers=&Apache::lonnet::getversion($1);
                'vu' => 'Set Version to be used in '.$type,   if ($getvers>0) {
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      $newsetversions{$1}=$getvers;
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      &devalidateversioncache($1);
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',   }
        'di' => 'Differences');      }
     $r->print(<<ENDHEADERS);   }
 <form action="/adm/coursedocs" method="post">      } elsif ($env{'form.setversions'}) {
 <input type="hidden" name="versions" value="1" />   $haschanged=1;
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />   foreach my $key (keys(%env)) {
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />      if ($key=~/^form\.set_version_(.+)$/) {
 <select name="timerange">   my $src=$1;
 <option value='all' $allsel>$lt{'al'}</option>   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
 <option value="-1" $startsel>$lt{'st'}</option>      $newsetversions{$src}=$env{$key};
 <option value="2592000" $monthsel>$lt{'lm'}</option>      &devalidateversioncache($src);
 <option value="604800" $weeksel>$lt{'lw'}</option>   }
 <option value="86400" $daysel>$lt{'sy'}</option>      }
 </select>   }
 <input type="submit" name="display" value="$lt{'sd'}" />      }
 <h3>$header</h3>      if ($haschanged) {
 <input type="submit" name="setversions" value="$lt{'sv'}" />          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
 <table border="0">    $env{'course.'.$env{'request.course.id'}.'.domain'},
 ENDHEADERS    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
     foreach my $key (sort(keys(%changes))) {      $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
  if ($changes{$key}>$starttime) {   } else {
     my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);      $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
     my $currentversion=&Apache::lonnet::getversion($key);   }
     if ($currentversion<0) {   &mark_hash_old();
  $currentversion=&mt('Could not be determined.');      }
     }      &changewarning($r,'');
     my $linkurl=&Apache::lonnet::clutter($key);      if ($env{'form.timerange'} eq 'all') {
     $r->print(  # show all documents
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.   $header=&mt('All Documents in '.$crstype);
       &Apache::lonnet::gettitle($linkurl).   $allsel=1;
                       '</b></font></td></tr>'.   foreach my $key (keys(%hash)) {
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      if ($key=~/^ids\_(\/res\/.+)$/) {
                       '<td colspan="4">'.   my $src=$1;
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.   $changes{$src}=1;
       '</a></td></tr>'.      }
                       '<tr><td></td>'.   }
                       '<td title="'.$lt{'md'}.'">'.      } else {
       &Apache::lonlocal::locallocaltime(  # show documents which changed
                            &Apache::lonnet::metadata($root.'.'.$extension,   %changes=&Apache::lonnet::dump
                                                      'lastrevisiondate')   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
                                                         ).                       $env{'course.'.$env{'request.course.id'}.'.num'});
                       '</td>'.   my $firstkey=(keys(%changes))[0];
                       '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.   unless ($firstkey=~/^error\:/) {
                       '<font size="+1">'.$currentversion.'</font>'.      unless ($env{'form.timerange'}) {
                       '</span></td>'.   $env{'form.timerange'}=604800;
                       '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.      }
                       '<font size="+1">');      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 # Used in course   .&mt('seconds');
     my $usedversion=$hash{'version_'.$linkurl};      if ($env{'form.timerange'}==-1) {
     if (($usedversion) && ($usedversion ne 'mostrecent')) {   $seltext='since start of course';
  $r->print($usedversion);   $startsel='selected';
     } else {   $env{'form.timerange'}=time;
  $r->print($currentversion);      }
     }      $starttime=time-$env{'form.timerange'};
     $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.      if ($env{'form.timerange'}==2592000) {
                       '<span class="LC_nobreak">Use: ');   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 # Set version   $monthsel='selected';
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},      } elsif ($env{'form.timerange'}==604800) {
       'set_version_'.$linkurl,   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
       ('select_form_order' =>   $weeksel='selected';
        ['',1..$currentversion,'mostrecent'],      } elsif ($env{'form.timerange'}==86400) {
        '' => '',   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
        'mostrecent' => 'most recent',   $daysel='selected';
        map {$_,$_} (1..$currentversion))));      }
     $r->print('</span></td></tr><tr><td></td>');      $header=&mt('Content changed').' '.$seltext;
     my $lastold=1;   } else {
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {      $header=&mt('No content modifications yet.');
  my $url=$root.'.'.$prevvers.'.'.$extension;   }
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<      }
     $starttime) {      %setversions=&Apache::lonnet::dump('resourceversions',
     $lastold=$prevvers;    $env{'course.'.$env{'request.course.id'}.'.domain'},
  }    $env{'course.'.$env{'request.course.id'}.'.num'});
     }      my %lt=&Apache::lonlocal::texthash
             #        ('st' => 'Version changes since start of '.$crstype,
             # Code to figure out how many version entries should go in         'lm' => 'Version changes since last Month',
             # each of the four columns         'lw' => 'Version changes since last Week',
             my $entries_per_col = 0;         'sy' => 'Version changes since Yesterday',
             my $num_entries = ($currentversion-$lastold);                 'al' => 'All Resources (possibly large output)',
             if ($num_entries % 4 == 0) {         'sd' => 'Display',
                 $entries_per_col = $num_entries/4;         'fi' => 'File',
             } else {         'md' => 'Modification Date',
                 $entries_per_col = $num_entries/4 + 1;                 'mr' => 'Most recently published Version',
             }         've' => 'Version used in '.$crstype,
             my $entries_count = 0;                 'vu' => 'Set Version to be used in '.$crstype,
             $r->print('<td valign="top"><font size="-2">');  'sv' => 'Set Versions to be used in '.$crstype.' according to Selections below',
             my $cols_output = 1;  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
  my $url=$root.'.'.$prevvers.'.'.$extension;         'di' => 'Differences');
  $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).      $r->print(<<ENDHEADERS);
   '">'.&mt('Version').' '.$prevvers.'</a> ('.  <form action="/adm/coursedocs" method="post">
   &Apache::lonlocal::locallocaltime(  <input type="hidden" name="versions" value="1" />
                                 &Apache::lonnet::metadata($url,  <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
                                                           'lastrevisiondate')  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
                                                             ).  <select name="timerange">
   ')');  <option value='all' $allsel>$lt{'al'}</option>
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {  <option value="-1" $startsel>$lt{'st'}</option>
                     $r->print(' <a href="/adm/diff?filename='.  <option value="2592000" $monthsel>$lt{'lm'}</option>
       &Apache::lonnet::clutter($root.'.'.$extension).  <option value="604800" $weeksel>$lt{'lw'}</option>
       '&versionone='.$prevvers.  <option value="86400" $daysel>$lt{'sy'}</option>
       '">'.&mt('Diffs').'</a>');  </select>
  }  <input type="submit" name="display" value="$lt{'sd'}" />
  $r->print('</span><br />');  <h3>$header</h3>
                 if (++$entries_count % $entries_per_col == 0) {  <input type="submit" name="setversions" value="$lt{'sv'}" />
                     $r->print('</font></td>');  <table border="0">
                     if ($cols_output != 4) {  ENDHEADERS
                         $r->print('<td valign="top"><font size="-2">');      foreach my $key (sort(keys(%changes))) {
                         $cols_output++;   if ($changes{$key}>$starttime) {
                     }      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
                 }      my $currentversion=&Apache::lonnet::getversion($key);
     }      if ($currentversion<0) {
             while($cols_output++ < 4) {   $currentversion=&mt('Could not be determined.');
                 $r->print('</font></td><td><font>')      }
             }      my $linkurl=&Apache::lonnet::clutter($key);
     $r->print('</font></td></tr>'."\n");      $r->print(
  }        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
     }        &Apache::lonnet::gettitle($linkurl).
     $r->print('</table></form>');                        '</b></font></td></tr>'.
     $r->print('<h1>'.&mt('Done').'.</h1>');                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
                         '<td colspan="4">'.
     &untiehash();                        '<a href="'.$linkurl.'" target="cat">'.$linkurl.
 }        '</a></td></tr>'.
                         '<tr><td></td>'.
 sub mark_hash_old {                        '<td title="'.$lt{'md'}.'">'.
     my $retie_hash=0;        &Apache::lonlocal::locallocaltime(
     if ($hashtied) {                             &Apache::lonnet::metadata($root.'.'.$extension,
  $retie_hash=1;                                                       'lastrevisiondate')
  &untiehash();                                                          ).
     }                        '</td>'.
     &tiehash('write');                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
     $hash{'old'}=1;                        '<font size="+1">'.$currentversion.'</font>'.
     &untiehash();                        '</span></td>'.
     if ($retie_hash) { &tiehash(); }                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$crstype.': '.
 }                        '<font size="+1">');
   # Used in course
 sub is_hash_old {      my $usedversion=$hash{'version_'.$linkurl};
     my $untie_hash=0;      if (($usedversion) && ($usedversion ne 'mostrecent')) {
     if (!$hashtied) {   $r->print($usedversion);
  $untie_hash=1;      } else {
  &tiehash();   $r->print($currentversion);
     }      }
     my $return=$hash{'old'};      $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
     if ($untie_hash) { &untiehash(); }                        '<span class="LC_nobreak">Use: ');
     return $return;  # Set version
 }      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
         'set_version_'.$linkurl,
 sub changewarning {        ('select_form_order' =>
     my ($r,$postexec,$message,$url)=@_;         ['',1..$currentversion,'mostrecent'],
     if (!&is_hash_old()) { return; }         '' => '',
     my $pathvar='folderpath';         'mostrecent' => &mt('most recent'),
     my $path=&escape($env{'form.folderpath'});         map {$_,$_} (1..$currentversion))));
     if (!defined($url)) {      $r->print('</span></td></tr><tr><td></td>');
  if (defined($env{'form.pagepath'})) {      my $lastold=1;
     $pathvar='pagepath';      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
     $path=&escape($env{'form.pagepath'});   my $url=$root.'.'.$prevvers.'.'.$extension;
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
  }      $starttime) {
  $url='/adm/coursedocs?'.$pathvar.'='.$path;      $lastold=$prevvers;
     }   }
     my $course_type = &Apache::loncommon::course_type();      }
     if (!defined($message)) {              #
  $message='Changes will become active for your current session after [_1], or the next time you log in.';              # Code to figure out how many version entries should go in
     }              # each of the four columns
     $r->print("\n\n".              my $entries_per_col = 0;
 '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".              my $num_entries = ($currentversion-$lastold);
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.              if ($num_entries % 4 == 0) {
 '<input type="hidden" name="orgurl" value="'.$url.                  $entries_per_col = $num_entries/4;
 '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.              } else {
 &mt($message,' <input type="hidden" name="'.                  $entries_per_col = $num_entries/4 + 1;
     $env{'request.role'}.'" value="1" /><input type="button" value="'.              }
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').              my $entries_count = 0;
 $help{'Caching'}.'</span></h3></form>'."\n\n");              $r->print('<td valign="top"><font size="-2">');
 }              my $cols_output = 1;
               for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
    my $url=$root.'.'.$prevvers.'.'.$extension;
 sub init_breadcrumbs {   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
     my ($form,$text)=@_;    '">'.&mt('Version').' '.$prevvers.'</a> ('.
     &Apache::lonhtmlcommon::clear_breadcrumbs();    &Apache::lonlocal::locallocaltime(
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",                                  &Apache::lonnet::metadata($url,
     text=>"Edit ".&Apache::loncommon::course_type(),                                                            'lastrevisiondate')
     faq=>273,                                                              ).
     bug=>'Instructor Interface',    ')');
                                             help => 'Docs_Adding_Course_Doc'});   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',                      $r->print(' <a href="/adm/diff?filename='.
     text=>$text,        &Apache::lonnet::clutter($root.'.'.$extension).
     faq=>273,        '&versionone='.$prevvers.
     bug=>'Instructor Interface'});        '">'.&mt('Diffs').'</a>');
 }   }
    $r->print('</span><br />');
                   if (++$entries_count % $entries_per_col == 0) {
                       $r->print('</font></td>');
                       if ($cols_output != 4) {
 sub handler {                          $r->print('<td valign="top"><font size="-2">');
     my $r = shift;                          $cols_output++;
     &Apache::loncommon::content_type($r,'text/html');                      }
     $r->send_http_header;                  }
     return OK if $r->header_only;      }
     my $type = &Apache::loncommon::course_type();              while($cols_output++ < 4) {
                   $r->print('</font></td><td><font>')
               }
 # --------------------------------------------- Initialize help topics for this      $r->print('</font></td></tr>'."\n");
     foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',   }
                'Adding_External_Resource','Navigate_Content',      }
                'Adding_Folders','Docs_Overview', 'Load_Map',      $r->print('</table></form>');
                'Supplemental','Score_Upload_Form','Adding_Pages',      $r->print('<h1>'.&mt('Done').'.</h1>');
                'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',  
                'Check_Resource_Versions','Verify_Content') {      &untiehash();
  $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);  }
     }  
     # Composite help files  sub mark_hash_old {
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(      my $retie_hash=0;
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');      if ($hashtied) {
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(   $retie_hash=1;
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');   &untiehash();
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(      }
     'Option_Response_Simple');      &tiehash('write');
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(      $hash{'old'}=1;
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');      &untiehash();
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(      if ($retie_hash) { &tiehash(); }
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');  }
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');  
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');  sub is_hash_old {
       my $untie_hash=0;
 # does this user have privileges to modify docs      if (!$hashtied) {
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});   $untie_hash=1;
   if ($allowed && $env{'form.verify'}) {   &tiehash();
       &init_breadcrumbs('verify','Verify Content');      }
       &verifycontent($r);      my $return=$hash{'old'};
   } elsif ($allowed && $env{'form.listsymbs'}) {      if ($untie_hash) { &untiehash(); }
       &init_breadcrumbs('listsymbs','List Symbs');      return $return;
       &list_symbs($r);  }
   } elsif ($allowed && $env{'form.docslog'}) {  
       &init_breadcrumbs('docslog','Show Log');  sub changewarning {
       &docs_change_log($r);      my ($r,$postexec,$message,$url)=@_;
   } elsif ($allowed && $env{'form.versions'}) {      if (!&is_hash_old()) { return; }
       &init_breadcrumbs('versions','Check/Set Resource Versions');      my $pathvar='folderpath';
       &checkversions($r);      my $path=&escape($env{'form.folderpath'});
   } elsif ($allowed && $env{'form.dumpcourse'}) {      if (!defined($url)) {
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');   if (defined($env{'form.pagepath'})) {
       &dumpcourse($r);      $pathvar='pagepath';
   } elsif ($allowed && $env{'form.exportcourse'}) {      $path=&escape($env{'form.pagepath'});
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
       &exportcourse($r);   }
   } else {   $url='/adm/coursedocs?'.$pathvar.'='.$path;
 # is this a standard course?      }
       my $course_type = &Apache::loncommon::course_type();
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);      if (!defined($message)) {
     my $forcestandard = 0;   $message='Changes will become active for your current session after [_1], or the next time you log in.';
     my $forcesupplement;      }
     my $script='';      $r->print("\n\n".
     my $showdoc=0;  '<script type="text/javascript">'."\n".
     my $containertag;  '// <![CDATA['."\n".
     my $uploadtag;  'function reinit(tf) { tf.submit();'.$postexec.' }'."\n".
   '// ]]>'."\n".
   '</script>'."\n".
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
     ['folderpath','pagepath',  '<input type="hidden" name="orgurl" value="'.$url.
      'pagesymb']);  '" /><input type="hidden" name="selectrole" value="1" /><p class="LC_warning">'.
 # No folderpath, no pagepath, see if we have something stored  &mt($message,' <input type="hidden" name="'.
     if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {      $env{'request.role'}.'" value="1" /><input type="button" value="'.
         &Apache::loncommon::restore_course_settings('docs_folderpath',      &mt('re-initializing '.$course_type).'" onclick="reinit(this.form)" />').
                                               {'folderpath' => 'scalar'});  $help{'Caching'}.'</p></form>'."\n\n");
     }  }
     if (!$env{'form.folderpath'}) {  
         &Apache::loncommon::restore_course_settings('docs_folderpath',  
                                               {'pagepath' => 'scalar'});  sub init_breadcrumbs {
     }      my ($form,$text)=@_;
     if ($env{'form.pagepath'}) {      &Apache::lonhtmlcommon::clear_breadcrumbs();
        $env{'form.folderpath'}='';      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
     }      text=>&Apache::loncommon::course_type().' Editor',
     if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {      faq=>273,
         $env{'form.folderpath'} = 'supplemental&'.      bug=>'Instructor Interface',
                                   &escape(&mt('Supplemental '.$type.' Documents')).'&'.                                              help => 'Docs_Adding_Course_Doc'});
                                   $env{'form.folderpath'};      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
     }      text=>$text,
     &Apache::loncommon::store_course_settings('docs_folderpath',      faq=>273,
                                                 {'pagepath' => 'scalar',      bug=>'Instructor Interface'});
                                                  'folderpath' => 'scalar'});  }
     if ($env{'form.folderpath'}) {  
  my (@folderpath)=split('&',$env{'form.folderpath'});  
  $env{'form.foldername'}=&unescape(pop(@folderpath));  
  $env{'form.folder'}=pop(@folderpath);  
     }  sub handler {
     if ($env{'form.pagepath'}) {      my $r = shift;
         my (@pagepath)=split('&',$env{'form.pagepath'});      &Apache::loncommon::content_type($r,'text/html');
         $env{'form.pagename'}=&unescape(pop(@pagepath));      $r->send_http_header;
         $env{'form.folder'}=pop(@pagepath);      return OK if $r->header_only;
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      my $crstype = &Apache::loncommon::course_type();
     '<input type="hidden" name="pagesymb" value="" />';  
         $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.  
     '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';  # --------------------------------------------- Initialize help topics for this
     }      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {                 'Adding_External_Resource','Navigate_Content',
        $showdoc='/'.$1;                 'Adding_Folders','Docs_Overview', 'Load_Map',
     }                 'Supplemental','Score_Upload_Form','Adding_Pages',
     unless ($showdoc) { # got called from remote                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||                 'Check_Resource_Versions','Verify_Content') {
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
            $forcestandard = 1;      }
        }      # Composite help files
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
        if ($allowed) {      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
          $script=&Apache::lonratedt::editscript('simple');      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
        }      'Option_Response_Simple');
     } else { # got called in sequence from course      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
        $allowed=0;      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
     }      $help{'My Personal Information Page'} = &Apache::loncommon::help_open_topic(
     'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 # get course data      $help{'Group Portfolio'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};  
   # does this user have privileges to modify docs
 # get personal data      my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
     my $uname=$env{'user.name'};    if ($allowed && $env{'form.verify'}) {
     my $udom=$env{'user.domain'};        &init_breadcrumbs('verify','Verify Content');
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));        &verifycontent($r);
     } elsif ($allowed && $env{'form.listsymbs'}) {
 # graphics settings        &init_breadcrumbs('listsymbs','List Symbs');
         &list_symbs($r);
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");    } elsif ($allowed && $env{'form.docslog'}) {
         &init_breadcrumbs('docslog','Show Log');
     if ($allowed) {        &docs_change_log($r);
  $script .= &editing_js($udom,$uname);    } elsif ($allowed && $env{'form.versions'}) {
     }        &init_breadcrumbs('versions','Check/Set Resource Versions');
 # -------------------------------------------------------------------- Body tag        &checkversions($r);
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';    } elsif ($allowed && $env{'form.dumpcourse'}) {
     my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,        &dumpcourse($r);
     {'force_register' => $showdoc,    } elsif ($allowed && $env{'form.exportcourse'}) {
                                      'bread_crumbs' => $brcrum}).        &init_breadcrumbs('exportcourse','IMS Export');
       &Apache::loncommon::help_open_menu('','',273,'RAT'));        &exportcourse($r);
      } else {
   my %allfiles = ();  # is this a standard course?
   my %codebase = ();  
   my ($upload_result,$upload_output);      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
   if ($allowed) {      my $forcestandard = 0;
       if (($env{'form.uploaddoc.filename'}) &&      my $forcesupplement;
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {      my $script='';
 # Process file upload - phase one - upload and parse primary file.        my $showdoc=0;
   undef($hadchanges);      my $containertag;
           $upload_result = &process_file_upload(\$upload_output,$coursenum,      my $uploadtag;
  $coursedom,\%allfiles,  
  \%codebase,$1);  
   if ($hadchanges) {      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
       &mark_hash_old();      ['folderpath','pagepath',
   }       'pagesymb']);
           if ($upload_result eq 'phasetwo') {  # No folderpath, no pagepath, see if we have something stored
               $r->print($upload_output);      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
           }          &Apache::loncommon::restore_course_settings('docs_folderpath',
       } elsif ($env{'form.phasetwo'}) {                                                {'folderpath' => 'scalar'});
           my %newname = ();      }
           my %origname = ();      if (!$allowed) {
           my %attribs = ();          unless($env{'form.folderpath'} =~ /^supplemental/) {
           my $updateflag = 0;              $env{'form.folderpath'} = '';
           my $residx = $env{'form.newidx'};          }
           my $primary_url = &unescape($env{'form.primaryurl'});      }
 # Process file upload - phase two - gather secondary files.      if (!$env{'form.folderpath'} && $allowed) {
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {          &Apache::loncommon::restore_course_settings('docs_folderpath',
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                                                {'pagepath' => 'scalar'});
                   my $javacodebase;      }
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);      if ($env{'form.pagepath'}) {
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});         $env{'form.folderpath'}='';
                   if (exists($env{'form.embedded_codebase_'.$i})) {      }
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});        if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;          $env{'form.folderpath'} = 'supplemental&'.
                   }                                    &escape(&mt('Supplemental '.$crstype.' Documents')).'&'.
                   my @attributes = ();                                    $env{'form.folderpath'};
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {      }
                       @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});      &Apache::loncommon::store_course_settings('docs_folderpath',
                   } else {                                                  {'pagepath' => 'scalar',
                       @attributes = ($env{'form.embedded_attrib_'.$i});                                                   'folderpath' => 'scalar'});
                   }      if ($env{'form.folderpath'}) {
                   foreach my $attr (@attributes) {   my (@folderpath)=split('&',$env{'form.folderpath'});
                       push(@{$attribs{$i}},&unescape($attr));   $env{'form.foldername'}=&unescape(pop(@folderpath));
                   }   $env{'form.folder'}=pop(@folderpath);
                   if ($javacodebase) {      }
                       $codebase{$i} = $javacodebase;      if ($env{'form.pagepath'}) {
                       $codebase{$i} =~ s#/$##;          my (@pagepath)=split('&',$env{'form.pagepath'});
                       $updateflag = 1;          $env{'form.pagename'}=&unescape(pop(@pagepath));
                   }          $env{'form.folder'}=pop(@pagepath);
               }          $containertag = '<input type="hidden" name="pagepath" value="" />'.
               unless ($newname{$i} eq $origname{$i}) {      '<input type="hidden" name="pagesymb" value="" />';
                   $updateflag = 1;          $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
               }      '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
           }      }
 # Process file upload - phase three - modify primary file      if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
           if ($updateflag) {         $showdoc='/'.$1;
               my ($content,$rtncode);      }
               my $updateflag = 0;      if ($showdoc) { # got called in sequence from course
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);   $allowed=0; 
               if ($getstatus eq 'ok') {      } else {
                   foreach my $item (keys(%newname)) {         if (($env{'form.folder'}=~/^(?:group|default)_/) ||
                       if ($newname{$item} ne $origname{$item}) {            ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
                           my $attrib_regexp = '';             $forcestandard = 1;
                           if (@{$attribs{$item}} > 1) {         }
                               $attrib_regexp = join('|',@{$attribs{$item}});         $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
                           } else {  
                               $attrib_regexp = $attribs{$item}[0];         if ($allowed) {
                           }           &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {           $script=&Apache::lonratedt::editscript('simple');
                           }         }
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;      }
                       }  
                       if (exists($codebase{$item})) {  # subroutine to list form elements
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs  sub create_list_elements {
                       }     my @formarr = @_; 
                   }     my $list = '';
 # Save edited file.     for my $button (@formarr){
                   my $saveresult;   for my $picture(keys %$button) {
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};   #my $link = Apache::lonhtmlcommon::htmltag('a' ,$button->{$picture}, {href => "test"}); 
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};   $list .= Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text'});
                   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);     return $list;
               }  }
           }  
       }  # subroutine to create ul from list elements
   }  sub create_form_ul {
      my $list = shift;
   unless ($showdoc ||  $upload_result eq 'phasetwo') {     my $ul = Apache::lonhtmlcommon::htmltag('ul',$list, {class => 'LC_ListStyleNormal'});
 # -----------------------------------------------------------------------------     return $ul;
        my %lt=&Apache::lonlocal::texthash(  }
                 'uplm' => 'Upload a new main '.lc($type).' document',  
                 'upls' => 'Upload a new supplemental '.lc($type).' document',  # get course data
                 'impp' => 'Import a document',      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
                 'pubd' => 'Published Documents',      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
  'copm' => 'All documents out of a published map into this folder',  
                 'upld' => 'Upload Document',  # get personal data
                 'srch' => 'Search',      my $uname=$env{'user.name'};
                 'impo' => 'Import',      my $udom=$env{'user.domain'};
  'book' => 'Import Bookmarks',      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
                 'selm' => 'Select Map',  
                 'load' => 'Load Map',  # graphics settings
                 'reco' => 'Recover Deleted Resources',  
                 'newf' => 'New Folder',      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
                 'newp' => 'New Composite Page',  
                 'extr' => 'External Resource',      if ($allowed) {
                 'syll' => 'Syllabus',   $script .= &editing_js($udom,$uname);
                 'navc' => 'Navigate Contents',      }
                 'sipa' => 'Simple Page',  # -------------------------------------------------------------------- Body tag
                 'sipr' => 'Simple Problem',      $script = '<script type="text/javascript">'."\n"
                 'drbx' => 'Drop Box',                .'// <![CDATA['."\n"
                 'scuf' => 'Score Upload Form',                .$script."\n"
                 'bull' => 'Bulletin Board',                .'// ]]>'."\n"
                 'mypi' => 'My Personal Info',                .'</script>'."\n";
                 'grpo' => 'Group Files',  
                 'rost' => 'Course Roster',      # Breadcrumbs
  'abou' => 'About User',      &Apache::lonhtmlcommon::clear_breadcrumbs();
                 'imsf' => 'Import IMS package',      if ($allowed) {
                 'file' =>  'File',          &Apache::lonhtmlcommon::add_breadcrumb({
                 'title' => 'Title',              href=>"/adm/coursedocs",text=>"$crstype Editor"});
                 'comment' => 'Comment',  
                 'parse' => 'Upload embedded images/multimedia files if HTML file!',          $r->print(&Apache::loncommon::start_page("$crstype Editor", $script,
  'nd' => 'New Document',                                                   {'force_register' => $showdoc,})
  'pm' => 'Published Map',                   .&Apache::loncommon::help_open_menu('','',273,'RAT')
  'sd' => 'Special Document',                   .&Apache::lonhtmlcommon::breadcrumbs(
  'mo' => 'More Options',                       'Editing the Table of Contents for your '.$crstype,
  'hao' => 'Hide all Options'                       'Docs_Adding_Course_Doc')
   );          );
 # -----------------------------------------------------------------------------      } elsif ($showdoc) {
  my $fileupload=(<<FIUP);          $r->print(&Apache::loncommon::start_page("$crstype documents",undef,
  $lt{'file'}:<br />                                                  {'force_register' => $showdoc,}));
  <input type="file" name="uploaddoc" size="40" />      } else {
 FIUP          my $folder=$env{'form.folder'};
           if ($folder eq '' || $folder eq 'supplemental') {
  my $checkbox=(<<CHBO);              $env{'form.folderpath'} = 'supplemental&'.
  <!-- <label>$lt{'parse'}?                                        &escape(&mt('Supplemental '.$crstype.' Documents'));
  <input type="checkbox" name="parserflag" />          }
  </label> -->          my ($breadcrumbtrail) = &breadcrumbs($allowed,$crstype);
  <label>          $r->print(&Apache::loncommon::start_page("Supplemental documents").
  <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}                    $breadcrumbtrail);
  </label>      }
 CHBO  
     my %allfiles = ();
  my $fileuploadform=(<<FUFORM);    my %codebase = ();
  <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">    my ($upload_result,$upload_output);
  $fileupload    if ($allowed) {
  <br />        if (($env{'form.uploaddoc.filename'}) &&
  $lt{'title'}:<br />    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
  <input type="text" size="50" name="comment" />  # Process file upload - phase one - upload and parse primary file.
  $uploadtag    undef($hadchanges);
  <input type="hidden" name="cmd" value="upload_default" />            $upload_result = &process_file_upload(\$upload_output,$coursenum,
  <br />   $coursedom,\%allfiles,
  <span class="LC_nobreak">   \%codebase,$1);
  $checkbox    if ($hadchanges) {
  </span>        &mark_hash_old();
  <br />    }
  <br />            if ($upload_result eq 'phasetwo') {
  <span class="LC_nobreak">                $r->print($upload_output);
  <input type="submit" value="$lt{'upld'}" />            }
  $help{'Uploading_From_Harddrive'}        } elsif ($env{'form.phasetwo'}) {
  </span>            my %newname = ();
  </form>            my %origname = ();
 FUFORM            my %attribs = ();
             my $updateflag = 0;
  my $simpleeditdefaultform=(<<SEDFFORM);            my $residx = $env{'form.newidx'};
  <form action="/adm/coursedocs" method="post" name="simpleeditdefault">            my $primary_url = &unescape($env{'form.primaryurl'});
  $lt{'pubd'}<br />  # Process file upload - phase two - gather secondary files.
  $uploadtag            for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
  <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />                if ($env{'form.embedded_item_'.$i.'.filename'}) {
  <br />                    my $javacodebase;
  <span class="LC_nobreak">                    $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
  <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />                    $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
  $help{'Importing_LON-CAPA_Resource'}                    if (exists($env{'form.embedded_codebase_'.$i})) {
  </span>                        $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});
  <br />                        $origname{$i} =~ s#^\Q$javacodebase\E/##;
  <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />                    }
  <hr />                    my @attributes = ();
  <p>                    if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
  $lt{'copm'}<br />                        @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
  <input type="text" size="40" name="importmap" /><br />                    } else {
  <span class="LC_nobreak"><input type="button"                        @attributes = ($env{'form.embedded_attrib_'.$i});
  onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"                    }
  value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />                    foreach my $attr (@attributes) {
  $help{'Load_Map'}</span>                        push(@{$attribs{$i}},&unescape($attr));
  </p>                    }
  </form>                    if ($javacodebase) {
 SEDFFORM                        $codebase{$i} = $javacodebase;
                         $codebase{$i} =~ s#/$##;
  my $extresourcesform=(<<ERFORM);                        $updateflag = 1;
  <form action="/adm/coursedocs" method="post" name="newext">                    }
  $uploadtag                }
  <input type="hidden" name="importdetail" value="" />                unless ($newname{$i} eq $origname{$i}) {
  <span class="LC_nobreak">                    $updateflag = 1;
  <input name="newext" type="button" onClick="javascript:makenewext('newext');"                }
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}            }
  </span>  # Process file upload - phase three - modify primary file
  </form>            if ($updateflag) {
 ERFORM                my ($content,$rtncode);
                 my $updateflag = 0;
     if ($allowed) {                my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
  &update_paste_buffer($coursenum,$coursedom);                if ($getstatus eq 'ok') {
        my $dumpbut=&dumpbutton();                    foreach my $item (keys(%newname)) {
        my $exportbut=&exportbutton();                        if ($newname{$item} ne $origname{$item}) {
        my %lt=&Apache::lonlocal::texthash(                            my $attrib_regexp = '';
  'vc' => 'Verify Content',                            if (@{$attribs{$item}} > 1) {
  'cv' => 'Check/Set Resource Versions',                                $attrib_regexp = join('|',@{$attribs{$item}});
  'ls' => 'List Symbs',                            } else {
                                          'sl' => 'Show Log'                                $attrib_regexp = $attribs{$item}[0];
   );                            }
                             if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
        my $folderpath=$env{'form.folderpath'};                            }
        if (!$folderpath) {                            $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
    if ($env{'form.folder'} eq '' ||                        }
        $env{'form.folder'} eq 'supplemental') {                        if (exists($codebase{$item})) {
        $folderpath='default&'.                            $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
    &escape(&mt('Main '.$type.' Documents'));                        }
    }                    }
        }  # Save edited file.
        unless ($env{'form.pagepath'}) {                    my $saveresult;
            $containertag = '<input type="hidden" name="folderpath" value="" />';                    my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
            $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';                    my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
        }                    my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
                 } else {
        $r->print(<<ENDCOURSEVERIFY);                    &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
 <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" />  
   $containertag    unless ($showdoc ||  $upload_result eq 'phasetwo') {
 </form>  # -----------------------------------------------------------------------------
 <form name="simpleedit" method="post" action="/adm/coursedocs">         my %lt=&Apache::lonlocal::texthash(
   <input type="hidden" name="importdetail" value="" />                  'uplm' => 'Upload a new main '.lc($crstype).' document',
   $uploadtag                  'upls' => 'Upload a new supplemental '.lc($crstype).' document',
 </form>                  'impp' => 'Import a document',
 <form action="/adm/coursedocs" method="post" name="courseverify">   'copm' => 'All documents out of a published map into this folder',
   <div class="LC_docs_course_commands">                  'upld' => 'Import Document',
                   'srch' => 'Search',
       <div>                  'impo' => 'Import',
         <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}   'book' => 'Import Bookmarks',
       </div>                  'selm' => 'Select Map',
       <div>                  'load' => 'Load Map',
         <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}                  'reco' => 'Recover Deleted Resources',
       </div>                  'newf' => 'New Folder',
         $dumpbut                  'newp' => 'New Composite Page',
         $exportbut                  'extr' => 'External Resource',
       <div>                  'syll' => 'Syllabus',
         <input type="submit" name="listsymbs" value="$lt{'ls'}" />                  'navc' => 'Navigate Contents',
       </div>                  'sipa' => 'Simple Course Page',
       <div>                  'sipr' => 'Simple Problem',
         <input type="hidden" name="folder" value="$env{'form.folder'}" />                  'drbx' => 'Drop Box',
         <input type="submit" name="docslog" value="$lt{'sl'}" />                  'scuf' => 'Score Upload Form',
       </div>                  'bull' => 'Discussion Board',
   </div>                  'mypi' => 'My Personal Information Page',
 </form>                  'grpo' => 'Group Portfolio',
 <div style="clear: both; height: 0px;">&nbsp;</div>                  'rost' => 'Course Roster',
 ENDCOURSEVERIFY   'abou' => 'Personal Information Page for a User',
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',                  'imsf' => 'IMS Import',
      &mt('Editing the Table of Contents for your '.$type)));                  'imsl' => 'Import IMS package',
     }                  'file' =>  'File',
 # --------------------------------------------------------- Standard documents                  'title' => 'Title',
     $r->print('<table class="LC_docs_documents">');                  'comment' => 'Comment',
                   'parse' => 'Upload embedded images/multimedia files if HTML file',
     if (($standard) && ($allowed) && (!$forcesupplement)) {   'nd' => 'Upload Document',
  $r->print('<tr><td class="LC_docs_document">');   'pm' => 'Published Map',
 #  '<h2>'.&mt('Main Course Documents').   'sd' => 'Special Document',
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');   'mo' => 'More Options',
        my $folder=$env{'form.folder'};    );
        if ($folder eq '' || $folder eq 'supplemental') {  # -----------------------------------------------------------------------------
            $folder='default';   my $fileupload=(<<FIUP);
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));   $lt{'file'}:<br />
            $uploadtag = '<input type="hidden" name="folderpath" value="'.   <input type="file" name="uploaddoc" size="40" />
        &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';  FIUP
        }  
        my $postexec='';   my $checkbox=(<<CHBO);
        if ($folder eq 'default') {   <!-- <label>$lt{'parse'}?
    $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');   <input type="checkbox" name="parserflag" />
        } else {   </label> -->
            #$postexec='self.close();';   <label>
        }   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
        $hadchanges=0;   </label>
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,  CHBO
    $upload_output,$type);  
        if ($error) {      my $fileuploada = "<input type='submit' value='".$lt{'upld'}."' /> $help{'Uploading_From_Harddrive'}";
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');   my $fileuploadform=(<<FUFORM);
        }   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
        if ($hadchanges) {   <input type="hidden" name="active" value="aa" />
    &mark_hash_old();   $fileupload
        }   <br />
        &changewarning($r,$postexec);   $lt{'title'}:<br />
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   <input type="text" size="50" name="comment" />
                      '.sequence';   $uploadtag
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.   <input type="hidden" name="cmd" value="upload_default" />
                      '.page';   <br />
  my $container='sequence';   <span class="LC_nobreak">
  if ($env{'form.pagepath'}) {   $checkbox
     $container='page';   </span>
  }  FUFORM
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;      #$list .= Apache::lonhtmlcommon::htmltag('li', $picture.' '.$button->{$picture}, {class => 'LC_menubuttons_inline_text'});
       #$fileuploadform .= create_form_ul(create_list_elements(@fileuploada));
       $fileuploadform .= create_form_ul(Apache::lonhtmlcommon::htmltag('li',$fileuploada,{class => 'LC_menubuttons_inline_text'}));
    $fileuploadform .= (<<FUFORM);
  my $recoverform=(<<RFORM);   </form>
  <form action="/adm/groupsort" method="post" name="recover">  FUFORM
  <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />  
  </form>   my $simpleeditdefaultform=(<<SEDFFORM);
 RFORM   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
    <input type="hidden" name="active" value="bb" />
  my $imspform=(<<IMSPFORM);  SEDFFORM
  <form action="/adm/imsimportdocs" method="post" name="ims">   my @simpleeditdefaultforma = ( 
  <input type="hidden" name="folder" value="$folder" />   { '<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 name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />   { '<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'}" },
  </form>   { '<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>" },
 IMSPFORM   );
    $simpleeditdefaultform .= create_form_ul(create_list_elements(@simpleeditdefaultforma));
  my $newnavform=(<<NNFORM);   $simpleeditdefaultform .=(<<SEDFFORM);
  <form action="/adm/coursedocs" method="post" name="newnav">   <hr />
  $uploadtag   <p>
  <input type="hidden" name="importdetail"   $lt{'copm'}<br />
  value="$lt{'navc'}=/adm/navmaps" />   <input type="text" size="40" name="importmap" /><br />
  <span class="LC_nobreak">   <span class="LC_nobreak"><input type="button"
  <input name="newnav" type="submit" value="$lt{'navc'}" />   onclick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
  $help{'Navigate_Content'}   value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
  </span>   $help{'Load_Map'}</span>
  </form>   </p>
 NNFORM   </form>
  my $newsmppageform=(<<NSPFORM);  SEDFFORM
  <form action="/adm/coursedocs" method="post" name="newsmppg">  
  $uploadtag   my $extresourcesform=(<<ERFORM);
  <input type="hidden" name="importdetail" value="" />   <form action="/adm/coursedocs" method="post" name="newext">
  <span class="LC_nobreak">   $uploadtag
  <input name="newsmppg" type="button" value="$lt{'sipa'}"   <input type="hidden" name="importdetail" value="" />
  onClick="javascript:makesmppage();" /> $help{'Simple Page'}   <a onclick="javascript:makenewext('newext');">$lt{'extr'}</a>$help{'Adding_External_Resource'}
  </span>   </form>
  </form>  ERFORM
 NSPFORM  
       if ($allowed) {
  my $newsmpproblemform=(<<NSPROBFORM);   &update_paste_buffer($coursenum,$coursedom);
  <form action="/adm/coursedocs" method="post" name="newsmpproblem">         my %lt=&Apache::lonlocal::texthash(
  $uploadtag   'vc' => 'Verify Content',
  <input type="hidden" name="importdetail" value="" />   'cv' => 'Check/Set Resource Versions',
  <span class="LC_nobreak">   'ls' => 'List Symbs',
  <input name="newsmpproblem" type="button" value="$lt{'sipr'}"                                           'sl' => 'Show Log'
  onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}    );
  </span>  
  </form>         my $folderpath=$env{'form.folderpath'};
          if (!$folderpath) {
 NSPROBFORM     if ($env{'form.folder'} eq '' ||
          $env{'form.folder'} eq 'supplemental') {
  my $newdropboxform=(<<NDBFORM);         $folderpath='default&'.
  <form action="/adm/coursedocs" method="post" name="newdropbox">     &escape(&mt('Main '.$crstype.' Documents'));
  $uploadtag           }
  <input type="hidden" name="importdetail" value="" />         }
  <span class="LC_nobreak">                   unless ($env{'form.pagepath'}) {
  <input name="newdropbox" type="button" value="$lt{'drbx'}"             $containertag = '<input type="hidden" name="folderpath" value="" />';
  onClick="javascript:makedropbox();" />             $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
  </span>                 }
  </form>   $r->print(<<HIDDENFORM);
 NDBFORM   <form name="renameform" method="post" action="/adm/coursedocs">
      <input type="hidden" name="title" />
  my $newexuploadform=(<<NEXUFORM);     <input type="hidden" name="cmd" />
  <form action="/adm/coursedocs" method="post" name="newexamupload">     <input type="hidden" name="markcopy" />
  $uploadtag     <input type="hidden" name="copyfolder" />
  <input type="hidden" name="importdetail" value="" />     $containertag
  <span class="LC_nobreak">   </form>
  <input name="newexamupload" type="button" value="$lt{'scuf'}"   <form name="simpleedit" method="post" action="/adm/coursedocs">
  onClick="javascript:makeexamupload();" />     <input type="hidden" name="importdetail" value="" />
  $help{'Score_Upload_Form'}     $uploadtag
  </span>   </form>
  </form>  HIDDENFORM
 NEXUFORM      }
   # --------------------------------------------------------- Main tab structure
  my $newbulform=(<<NBFORM);   
  <form action="/adm/coursedocs" method="post" name="newbul">      my $activeClass = 1;
  $uploadtag      my $active = '';
  <input type="hidden" name="importdetail" value="" />      my %tabtitles = (
  <span class="LC_nobreak">                         main => {
  <input name="newbulletin" type="button" value="$lt{'bull'}"                                   Course => &mt('Main Course Documents'),
  onClick="javascript:makebulboard();" />                                   Community => &mt('Main Community Documents'),
  $help{'Bulletin Board'}                                 },
  </span>                         supplemental => {
  </form>                                   Course => &mt('Supplemental Course Documents'),        
 NBFORM                                   Community => &mt('Supplemental Community Documents'),
                                  },
  my $newaboutmeform=(<<NAMFORM);                      );
  <form action="/adm/coursedocs" method="post" name="newaboutme">      if ($allowed) {
  $uploadtag          $r->print('<ul class="LC_TabContentBigger" id="mainnav">');
  <input type="hidden" name="importdetail"          if (($standard) && ($allowed) && (!$forcesupplement) && (($env{'form.folderpath'}=~/^default/) || $env{'form.folderpath'}eq"" || ($env{'form.pagepath'}))) {
  value="$plainname=/adm/$udom/$uname/aboutme" />              if($activeClass == 1){
  <span class="LC_nobreak">                  $active = 'class="active"';
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />          $activeClass = 0;
  $help{'My Personal Info'}      }
  </span>          }
  </form>          $r->print('<li '.$active.' onclick="javascript:showPage(this,\'mainCourseDocuments\',\'mainnav\',\'maincoursedoc\');"><a href="#"><b>'.$tabtitles{'main'}{$crstype}.'</b></a></li>');
 NAMFORM          $active = '';
           if (!$forcestandard || ($env{'form.folderpath'}=~/^supplemental/)) {
  my $newaboutsomeoneform=(<<NASOFORM);              if($activeClass == 1){
  <form action="/adm/coursedocs" method="post" name="newaboutsomeone">                  $active = 'class="active"';
  $uploadtag              }
  <input type="hidden" name="importdetail" value="" />          }
  <span class="LC_nobreak">          $r->print('<li '.$active.' onclick="javascript:showPage(this,\'supplCourseDocuments\',\'mainnav\',\'maincoursedoc\');"><a href="#"><b>'.$tabtitles{'supplemental'}{$crstype}.'</b></a></li>');
  <input name="newaboutsomeone" type="button" value="$lt{'abou'}"          $r->print('</ul>');
  onClick="javascript:makeabout();" />      } else {
  </span>          $r->print('<br />');
  </form>      }
 NASOFORM      $r->print('<div class="LC_Box" style="clear:both;margin:0;">'
                .'<div id="maincoursedoc" style="margin:0 0;padding:0 0;">');
   # --------------------------------------------------------- Standard documents
  my $newrosterform=(<<NROSTFORM);         my $savefolderpath;
  <form action="/adm/coursedocs" method="post" name="newroster">         $active = 'style="display: none;"';
  $uploadtag         if($activeClass == 0){
  <input type="hidden" name="importdetail"            $active = 'style="display: block;"';
  value="$lt{'rost'}=/adm/viewclasslist" />         }
  <span class="LC_nobreak">         if ($allowed) {
  <input name="newroster" type="submit" value="$lt{'rost'}" />         $r->print('<div class="LC_ContentBox" id="mainCourseDocuments" '.$active.'>');
  $help{'Course Roster'}         my $folder=$env{'form.folder'};
  </span>         if ($folder eq '' || $folder=~/^supplemental/) {
  </form>             $folder='default';
 NROSTFORM     $savefolderpath = $env{'form.folderpath'};
      $env{'form.folderpath'}='default&'.&escape($tabtitles{'main'}{$crstype});
        $r->print(<<ENDFORM);             $uploadtag = '<input type="hidden" name="folderpath" value="'.
          &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
 <ul class="LC_TabContent">         }
 <li>$lt{'nd'}</li>         my $postexec='';
 <li>$lt{'pm'}</li>         if ($folder eq 'default') {
 <li>$lt{'pubd'}</li>             $r->print('<script type="text/javascript">'."\n"
 <li>$lt{'sd'}</li>                      .'// <![CDATA['."\n"
 <li>$lt{'mo'}</li>                      .'this.window.name="loncapaclient";'."\n"
 <li>$lt{'hao'}</li>                      .'// ]]>'."\n"
 </ul>                      .'</script>'."\n"
          );
 <table class="LC_docs_adddocs">         } else {
 <!-- <tr>             #$postexec='self.close();';
 <th>$lt{'uplm'}</th>         }
 <th>$lt{'impp'}</th>         my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
 <th>$lt{'spec'}</th>                       '.sequence';
 </tr> -->         my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
 <tr>                       '.page';
 <td>   my $container='sequence';
 $fileuploadform   if ($env{'form.pagepath'}) {
 </td>      $container='page';
 <td>   }
 $simpleeditdefaultform   my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 <hr />  
 $recoverform  
 ENDFORM  
        unless ($env{'form.pagepath'}) {   my $recoverform=(<<RFORM);
    $r->print(<<ENDFORM);   <form action="/adm/groupsort" method="post" name="recover">
 <hr />   <a onclick="javascript:groupopen('$readfile',1,0)">$lt{'reco'}</a>
 $extresourcesform   </form>
  <br />  RFORM
 $imspform  
 ENDFORM   my $imspform=(<<IMSPFORM);
        }   <form action="/adm/imsimportdocs" method="post" name="ims">
        $r->print('</td><td>');   <input type="hidden" name="folder" value="$folder" />
        unless ($env{'form.pagepath'}) {   <a onclick="javascript:makeims();">$lt{'imsf'}</a>
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');   </form>
   IMSPFORM
   
    my $newnavform=(<<NNFORM);
  my $newpageform=(<<NPFORM);   <form action="/adm/coursedocs" method="post" name="newnav">
  <form action="/adm/coursedocs" method="post" name="newpage">   <input type="hidden" name="active" value="cc" />
  <input type="hidden" name="folderpath" value="$path" />   $uploadtag
  <input type="hidden" name="importdetail" value="" />   <input type="hidden" name="importdetail" 
  <span class="LC_nobreak">   value="$lt{'navc'}=/adm/navmaps" />
  <input name="newpage" type="button"   <a onclick="document.newnav.submit()">$lt{'navc'}</a>
  onClick="javascript:makenewpage(this.form,'$pageseq');"   $help{'Navigate_Content'}
  value="$lt{'newp'}" />$help{'Adding_Pages'}   </form>
  </span>  NNFORM
  </form>   my $newsmppageform=(<<NSPFORM);
 NPFORM   <form action="/adm/coursedocs" method="post" name="newsmppg">
    <input type="hidden" name="active" value="cc" />
  my $newfolderform=(<<NFFORM);   $uploadtag
  <form action="/adm/coursedocs" method="post" name="newfolder">   <input type="hidden" name="importdetail" value="" />
  <input type="hidden" name="folderpath" value="$path" />   <a onclick="javascript:makesmppage();"> $lt{'sipa'}</a>
  <input type="hidden" name="importdetail" value="" />   $help{'Simple Page'}
  <span class="LC_nobreak">   </form>
  <input name="newfolder" type="button"  NSPFORM
  onClick="javascript:makenewfolder(this.form,'$folderseq');"  
  value="$lt{'newf'}" />$help{'Adding_Folders'}   my $newsmpproblemform=(<<NSPROBFORM);
  </span>   <form action="/adm/coursedocs" method="post" name="newsmpproblem">
  </form>   <input type="hidden" name="active" value="cc" />
 NFFORM   $uploadtag
    <input type="hidden" name="importdetail" value="" />
  my $newsylform=(<<NSYLFORM);   <a onclick="javascript:makesmpproblem();">$lt{'sipr'}</a>
  <form action="/adm/coursedocs" method="post" name="newsyl">   $help{'Simple Problem'}
  $uploadtag   </form>
  <input type="hidden" name="importdetail"  
  value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />  NSPROBFORM
  <span class="LC_nobreak">  
  <input name="newsyl" type="submit" value="$lt{'syll'}" />   my $newdropboxform=(<<NDBFORM);
  $help{'Syllabus'}   <form action="/adm/coursedocs" method="post" name="newdropbox">
  </span>   <input type="hidden" name="active" value="cc" />
  </form>   $uploadtag
 NSYLFORM   <input type="hidden" name="importdetail" value="" />
    <a onclick="javascript:makedropbox();">$lt{'drbx'}</a>
  my $newgroupfileform=(<<NGFFORM);   </form>
  <form action="/adm/coursedocs" method="post" name="newgroupfiles">  NDBFORM
  $uploadtag  
  <input type="hidden" name="importdetail"   my $newexuploadform=(<<NEXUFORM);
  value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />   <form action="/adm/coursedocs" method="post" name="newexamupload">
  <span class="LC_nobreak">   <input type="hidden" name="active" value="cc" />
  <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />   $uploadtag
  $help{'Group Files'}   <input type="hidden" name="importdetail" value="" />
  </span>   <a onclick="javascript:makeexamupload();">$lt{'scuf'}</a>
  </form>   $help{'Score_Upload_Form'}
 NGFFORM   </form>
   NEXUFORM
   
            $r->print(<<ENDFORM);   my $newbulform=(<<NBFORM);
 <br />   <form action="/adm/coursedocs" method="post" name="newbul">
 $newfolderform   <input type="hidden" name="active" value="cc" />
 <br />   $uploadtag
 $newpageform   <input type="hidden" name="importdetail" value="" />
 <br />   <a onclick="javascript:makebulboard();" >$lt{'bull'}</a>
 $newsylform   $help{'Bulletin Board'}
 <br />   </form>
 $newnavform  NBFORM
 <br />  
 $newsmppageform   my $newaboutmeform=(<<NAMFORM);
 <br />   <form action="/adm/coursedocs" method="post" name="newaboutme">
 $newsmpproblemform   <input type="hidden" name="active" value="cc" />
 <br />   $uploadtag
 $newdropboxform   <input type="hidden" name="importdetail" 
 <br />   value="$plainname=/adm/$udom/$uname/aboutme" />
 $newexuploadform   <a onclick="document.newaboutme.submit()">$lt{'mypi'}</a>
 <br />   $help{'My Personal Information Page'}
 $newbulform   </form>
 <br />  NAMFORM
 $newaboutmeform  
 <br />   my $newaboutsomeoneform=(<<NASOFORM);
 $newaboutsomeoneform   <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
 <br />   <input type="hidden" name="active" value="cc" />
 $newgroupfileform   $uploadtag
 <br />   <input type="hidden" name="importdetail" value="" />
 $newrosterform   <a onclick="javascript:makeabout();">$lt{'abou'}</a>
 ENDFORM   </form>
        }  NASOFORM
        if ($env{'form.pagepath'}) {  
            $r->print(<<ENDBLOCK);  
 $newsmpproblemform   my $newrosterform=(<<NROSTFORM);
 <br />   <form action="/adm/coursedocs" method="post" name="newroster">
 $newexuploadform   <input type="hidden" name="active" value="cc" />
 ENDBLOCK   $uploadtag
        }   <input type="hidden" name="importdetail" 
        $r->print('</td></tr>'."\n".   value="$lt{'rost'}=/adm/viewclasslist" />
 '</table>');   <a onclick="document.newroster.submit()">$lt{'rost'}</a>
        $r->print('</td></tr>');   $help{'Course Roster'}
     }   </form>
 # ----------------------------------------------------- Supplemental documents  NROSTFORM
     if (!$forcestandard) {  
        $r->print('<tr><td class="LC_docs_document">');  my $specialdocumentsform;
 # '<h2>'.&mt('Supplemental Course Documents').  my @specialdocumentsforma;
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');  my $newfolderform;
        my $folder=$env{'form.folder'};  my $newfolderb;
        unless ($folder=~/^supplemental/) {  
    $folder='supplemental';         unless ($env{'form.pagepath'}) {
        }     my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
        if ($folder =~ /^supplemental$/ &&  
    (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {   my $newpageform=(<<NPFORM);
           $env{'form.folderpath'} = 'supplemental&'.   <form action="/adm/coursedocs" method="post" name="newpage">
                                     &escape(&mt('Supplemental '.$type.' Documents'));   <input type="hidden" name="folderpath" value="$path" />
        }   <input type="hidden" name="importdetail" value="" />
        my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$type);   <input type="hidden" name="active" value="cc" />
        if ($error) {   <a onclick="javascript:makenewpage(document.newpage,'$pageseq');">$lt{'newp'}</a>
    $r->print('<p><span class="LC_error">'.$error.'</span></p>');   $help{'Adding_Pages'}
        }   </form>
        if ($allowed) {  NPFORM
    my $folderseq=  
        '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.  
        '.sequence';   $newfolderform=(<<NFFORM);
    <form action="/adm/coursedocs" method="post" name="newfolder">
    my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');   <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
  my $supupdocform=(<<SUPDOCFORM);   <input type="hidden" name="active" value="aa" />
  <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">   <a onclick="javascript:makenewfolder(document.newfolder,'$folderseq');">$lt{'newf'}</a>$help{'Adding_Folders'}
  $fileupload   </form>
  <br />  NFFORM
  <br />  
  <span class="LC_nobreak">   my $newsylform=(<<NSYLFORM);
  $checkbox   <form action="/adm/coursedocs" method="post" name="newsyl">
  </span>   <input type="hidden" name="active" value="cc" />
  <br /><br />   $uploadtag
  $lt{'comment'}:<br />   <input type="hidden" name="importdetail" 
  <textarea cols=50 rows=4 name='comment'>   value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
  </textarea>   <a onclick="document.newsyl.submit()">$lt{'syll'}</a>
  <br />   $help{'Syllabus'}
  <input type="hidden" name="folderpath" value="$path" />  
  <input type="hidden" name="cmd" value="upload_supplemental" />   </form>
  <span class="LC_nobreak">  NSYLFORM
  <input type="submit" value="$lt{'upld'}" />  
  $help{'Uploading_From_Harddrive'}   my $newgroupfileform=(<<NGFFORM);
  </span>   <form action="/adm/coursedocs" method="post" name="newgroupfiles">
  </form>   <input type="hidden" name="active" value="cc" />
 SUPDOCFORM   $uploadtag
    <input type="hidden" name="importdetail"
  my $supnewfolderform=(<<SNFFORM);   value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
  <form action="/adm/coursedocs" method="post" name="supnewfolder">   <a onclick="document.newgroupfiles.submit()">$lt{'grpo'}</a>
  <input type="hidden" name="folderpath" value="$path" />   $help{'Group Portfolio'}
  <input type="hidden" name="importdetail" value="" />   </form>
  <span class="LC_nobreak">  NGFFORM
  <input name="newfolder" type="button"   @specialdocumentsforma=(
  onClick="javascript:makenewfolder(this.form,'$folderseq');"   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/page.png" alt="'.$lt{newp}.'"  onclick="javascript:makenewpage(document.newpage,"'.$pageseq.'");" />'=>$newpageform},
  value="$lt{'newf'}" /> $help{'Adding_Folders'}   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/syllabus.png" alt="'.$lt{syll}.'" onclick="document.newsyl.submit()" />'=>$newsylform},
  </span>   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/groupportfolio.png" alt="'.$lt{grpo}.'" onclick="document.newgroupfiles.submit()" />'=>$newgroupfileform},
  </form>   ); 
 SNFFORM  
         }
    push @specialdocumentsforma, ({'<img class="LC_noBorder LC_middle" src="/res/adm/pages/navigation.png" alt="'.$lt{navc}.'" onclick="document.newnav.submit()" />'=>$newnavform},
  my $supnewextform=(<<SNEFORM);   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simple.png" alt="'.$lt{sipa}.'" onclick="javascript:makesmppage();" />'=>$newsmppageform},
  <form action="/adm/coursedocs" method="post" name="supnewext">   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.$lt{sipr}.'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
  <input type="hidden" name="folderpath" value="$path" />   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/dropbox.png" alt="'.$lt{drbx}.'" onclick="javascript:makedropbox();" />'=>$newdropboxform},
  <input type="hidden" name="importdetail" value="" />   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.$lt{scuf}.'" onclick="javascript:makeexamupload();" />'=>$newexuploadform},
  <span class="LC_nobreak">   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/bchat.png" alt="'.$lt{bull}.'" onclick="javascript:makebulboard();" />'=>$newbulform},
  <input name="newext" type="button"   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="javascript:makebulboard();" />'=>$newaboutmeform},
  onClick="javascript:makenewext('supnewext');"   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/aboutme.png" alt="'.$lt{abou}.'" onclick="javascript:makeabout();" />'=>$newaboutsomeoneform},
  value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/chrt.png" alt="'.$lt{rost}.'" onclick="document.newroster.submit()" />'=>$newrosterform},);
  </span>  
  </form>   $specialdocumentsform = create_form_ul(create_list_elements(@specialdocumentsforma));
 SNEFORM  
   if($env{'form.pagepath'}) {
  my $supnewsylform=(<<SNSFORM);  
  <form action="/adm/coursedocs" method="post" name="supnewsyl">   @specialdocumentsforma=(
  <input type="hidden" name="folderpath" value="$path" />   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/simpprob.png" alt="'.&mt('Simple Problem').'" onclick="javascript:makesmpproblem();" />'=>$newsmpproblemform},
  <input type="hidden" name="importdetail"   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/scoreupfrm.png" alt="'.&mt('Score Upload Form').'" onclick="javascript:makeexamupload();" />'=>$newexuploadform}
  value="Syllabus=/public/$coursedom/$coursenum/syllabus" />   );
  <span class="LC_nobreak">   $specialdocumentsform= create_form_ul(create_list_elements(@specialdocumentsforma));
  <input name="newsyl" type="submit" value="$lt{'syll'}" />  }
  $help{'Syllabus'}  
  </span>  my @tools = (
  </form>  # {'<img class="LC_noBorder LC_middle" align="left" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" />'=>$extresourcesform},
 SNSFORM  # {'<img class="LC_noBorder LC_middle" align="left" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" />'=>$imspform},
    {'<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">  
  <input type="hidden" name="folderpath" value="$path" />  my @importdoc = (
  <input type="hidden" name="importdetail"      {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'newext\');" />'=>$extresourcesform},
  value="$plainname=/adm/$udom/$uname/aboutme" />      {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/ims.png" alt="'.$lt{imsf}.'" onclick="javascript:makeims();" />'=>$imspform}, 
  <span class="LC_nobreak">  );
  <input name="newaboutme" type="submit" value="$lt{'mypi'}" />  $fileuploadform =  create_form_ul(create_list_elements(@importdoc)) . '<hr/>' . $fileuploadform;
  $help{'My Personal Info'}  my %orderhash = (
  </span>   '00' => ['Newfolder',$newfolderform],
  </form>                  'aa' => ['Import Documents',$fileuploadform],
 SNAMFORM                  'bb' => ['Published Resources',$simpleeditdefaultform],
                   'cc' => ['Special Documents',$specialdocumentsform],
    $r->print(<<ENDSUPFORM);   'dd' => ['Tools', create_form_ul(create_list_elements(@tools)).&generate_admin_options($containertag,$uploadtag,\%help,\%env)],
 <ul class="LC_TabContent">                  );
 <li>$lt{'nd'}</li>  my $tid='1';
 <li>$lt{'sd'}</li>   $hadchanges=0;
 <li>$lt{'hao'}</li>          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype);
 </ul>         if ($error) {
 <table class="LC_docs_adddocs">             $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 <tr><td>         }
 $supupdocform         if ($hadchanges) {
 </td>             &mark_hash_old();
 <td>         }
 $supnewfolderform  
 <br />         &changewarning($r,'');
 $supnewextform  $r->print(&generate_edit_table($tid,\%orderhash));
 <br />  
 $supnewsylform  $r->print('</div>');
 <br />   }
 $supnewaboutmeform         if ($env{'form.pagepath'}) {
 </td></tr>         }
 </table></td></tr>  # ----------------------------------------------------- Supplemental documents
 ENDSUPFORM         $active = 'style="display: none;"';
        }         if($activeClass == 1){
     }            $active = 'style="display: block;"';
     $r->print('</table>');         }
     if ($allowed) {         $r->print('<div class="LC_ContentBox" id="supplCourseDocuments" '.$active.'>');
  $r->print('         my $folder=$env{'form.folder'};
 <form method="post" name="extimport" action="/adm/coursedocs">         unless ($folder=~/^supplemental/) {
   <input type="hidden" name="title" />     $folder='supplemental';
   <input type="hidden" name="url" />         }
   <input type="hidden" name="useform" />         if ($folder =~ /^supplemental$/ &&
   <input type="hidden" name="residx" />     (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
 </form>');            $env{'form.folderpath'} = 'supplemental&'.
     }                                      &escape(&mt('Supplemental '.$crstype.' Documents'));
   } else {         } elsif ($allowed) {
       unless ($upload_result eq 'phasetwo') {    $env{'form.folderpath'} = $savefolderpath;
 # -------------------------------------------------------- This is showdoc mode         }
           $r->print("<h1>".&mt('Uploaded Document').' - '.         $env{'form.pagepath'} = '';
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.         if ($allowed) {
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".     my $folderseq=
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');         '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.
       }         '.sequence';
   }  
  }     my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
  $r->print(&Apache::loncommon::end_page());  
  return OK;   my $supupdocformbtn = "<input type='submit' value='".$lt{'upld'}."' />$help{'Uploading_From_Harddrive'}";
 }   my $supupdocform=(<<SUPDOCFORM);
    <form action="/adm/coursedocs" method="post" name="supuploaddocument" enctype="multipart/form-data">
    <input type="hidden" name="active" value="ee" />
 sub editing_js {   $fileupload
     my ($udom,$uname) = @_;   <br />
     my $now = time();   <br />
     my %lt = &Apache::lonlocal::texthash(   <span class="LC_nobreak">
                                           p_mnf => 'Name of New Folder',   $checkbox
                                           t_mnf => 'New Folder',   </span>
                                           p_mnp => 'Name of New Page',   <br /><br />
                                           t_mnp => 'New Page',   $lt{'comment'}:<br />
                                           p_mxu => 'Title for the Uploaded Score',   <textarea cols="50" rows="4" name="comment"></textarea>
                                           p_msp => 'Title for the Page',   <br />
                                           p_msb => 'Title for the Problem',   <input type="hidden" name="folderpath" value="$path" />
                                           p_mdb => 'Title for the Drop Box',   <input type="hidden" name="cmd" value="upload_supplemental" />
                                           p_mbb => 'Title for the Bulletin Board',  SUPDOCFORM
                                           p_mab => "Enter user:domain for User's 'About Me' Page",   $supupdocform .=  create_form_ul(Apache::lonhtmlcommon::htmltag('li',$supupdocformbtn,{class => 'LC_menubuttons_inline_text'}))."</form>";
                                           p_mab2 => "About [_99]",  
                                           p_mab_alrt1 => 'Not a valid user:domain',   my $supnewfolderform=(<<SNFFORM);
                                           p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',   <form action="/adm/coursedocs" method="post" name="supnewfolder">
                                           p_chn => 'New Title',   <input type="hidden" name="active" value="ee" />
                                           p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',   <input type="hidden" name="folderpath" value="$path" />
                                           p_rmr2a => 'Remove[_99]',   <input type="hidden" name="importdetail" value="" />
                                           p_rmr2b => '?[_99]',   <a onclick="javascript:makenewfolder(document.supnewfolder,'$folderseq');">$lt{'newf'}</a> 
                                           p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',   $help{'Adding_Folders'}
                                           p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',   </form>
                                           p_ctr2a => 'Cut[_98]',  SNFFORM
                                           p_ctr2b => '?[_98]'  
                                         );  
    my $supnewextform=(<<SNEFORM);
     return <<ENDNEWSCRIPT;   <form action="/adm/coursedocs" method="post" name="supnewext">
 function makenewfolder(targetform,folderseq) {   <input type="hidden" name="active" value="ff" />
     var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');   <input type="hidden" name="folderpath" value="$path" />
     if (foldername) {   <input type="hidden" name="importdetail" value="" />
        targetform.importdetail.value=escape(foldername)+"="+folderseq;   <a onclick="javascript:makenewext('supnewext');">$lt{'extr'}</a> $help{'Adding_External_Resource'}
         targetform.submit();   </form>
     }  SNEFORM
 }  
    my $supnewsylform=(<<SNSFORM);
 function makenewpage(targetform,folderseq) {   <form action="/adm/coursedocs" method="post" name="supnewsyl">
     var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');   <input type="hidden" name="active" value="ff" />
     if (pagename) {   <input type="hidden" name="folderpath" value="$path" />
         targetform.importdetail.value=escape(pagename)+"="+folderseq;   <input type="hidden" name="importdetail" 
         targetform.submit();   value="Syllabus=/public/$coursedom/$coursenum/syllabus" />
     }   <a onclick="document.supnewsyl.submit()">$lt{'syll'}</a>
 }   $help{'Syllabus'}
    </form>
 function makenewext(targetname) {  SNSFORM
     this.document.forms.extimport.useform.value=targetname;  
     this.document.forms.extimport.title.value='';   my $supnewaboutmeform=(<<SNAMFORM);
     this.document.forms.extimport.url.value='';   <form action="/adm/coursedocs" method="post" name="supnewaboutme">
     this.document.forms.extimport.residx.value='';   <input type="hidden" name="active" value="ff" />
     window.open('/adm/rat/extpickframe.html');   <input type="hidden" name="folderpath" value="$path" />
 }   <input type="hidden" name="importdetail" 
    value="$plainname=/adm/$udom/$uname/aboutme" />
 function edittext(targetname,residx,title,url) {   <a onclick="document.supnewaboutme.submit()">$lt{'mypi'}</a>
     this.document.forms.extimport.useform.value=targetname;   $help{'My Personal Information Page'}
     this.document.forms.extimport.residx.value=residx;   </form>
     this.document.forms.extimport.url.value=url;  SNAMFORM
     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()" />'
 function makeexamupload() {              =>$supnewsylform},
    var title=prompt('$lt{"p_mxu"}');   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/myaboutme.png" alt="'.$lt{mypi}.'" onclick="document.supnewaboutme.submit()" />'
    if (title) {              =>$supnewaboutmeform},
     this.document.forms.newexamupload.importdetail.value=   );
  escape(title)+'=/res/lib/templates/examupload.problem';  my @supimportdoc = (
     this.document.forms.newexamupload.submit();   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/extres.png" alt="'.$lt{extr}.'" onclick="javascript:makenewext(\'supnewext\');" />'
    }              =>$supnewextform},
 }          );
   $supupdocform =  create_form_ul(create_list_elements(@supimportdoc)) . '<hr/>' . $supupdocform;
 function makesmppage() {  my %suporderhash = (
    var title=prompt('$lt{"p_msp"}');   '00' => ['Supnewfolder', $supnewfolderform],
    if (title) {                  'ee' => ['Import Documents',$supupdocform],
     this.document.forms.newsmppg.importdetail.value=                  'ff' => ['Special Documents',create_form_ul(create_list_elements(@specialdocs))]
  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() {          }
    var title=prompt('$lt{"p_msb"}');          my $tid='2';
    if (title) {          $r->print(&generate_edit_table($tid,\%suporderhash));
     this.document.forms.newsmpproblem.importdetail.value=      } else {
  escape(title)+'=/res/lib/templates/simpleproblem.problem';          my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,'',$crstype);
     this.document.forms.newsmpproblem.submit();          if ($error) {
    }              $r->print('<p><span class="LC_error">'.$error.'</span></p>');
 }          }
       }
 function makedropbox() {  
    var title=prompt('$lt{"p_mdb"}');  
    if (title) {  $r->print('</div>');
     this.document.forms.newdropbox.importdetail.value=  $r->print('</div></div>');
         escape(title)+'=/res/lib/templates/DropBox.problem';  
     this.document.forms.newdropbox.submit();  
    }      if ($allowed) {
 }   $r->print('
   <form method="post" name="extimport" action="/adm/coursedocs">
 function makebulboard() {    <input type="hidden" name="title" />
    var title=prompt('$lt{"p_mbb"}');    <input type="hidden" name="url" />
    if (title) {    <input type="hidden" name="useform" />
     this.document.forms.newbul.importdetail.value=    <input type="hidden" name="residx" />
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';  </form>');
     this.document.forms.newbul.submit();      }
    }    } else {
 }        unless ($upload_result eq 'phasetwo') {
   # -------------------------------------------------------- This is showdoc mode
 function makeabout() {            $r->print("<h1>".&mt('Uploaded Document').' - '.
    var user=prompt("$lt{'p_mab'}");   &Apache::lonnet::gettitle($r->uri).'</h1><p>'.
    if (user) {  &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><table>".
        var comp=new Array();            &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table>');
        comp=user.split(':');        }
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {    }
    if ((comp[0]) && (comp[1])) {   }
        this.document.forms.newaboutsomeone.importdetail.value=   $r->print(&Apache::loncommon::end_page());
    '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   return OK;
        this.document.forms.newaboutsomeone.submit();  }
    } else {  
                alert("$lt{'p_mab_alrt1'}");  sub generate_admin_options {
            }    my ($containertag,$uploadtag,$help_ref,$env_ref) = @_;
        } else {   my %lt=&Apache::lonlocal::texthash(
            alert("$lt{'p_mab_alrt2'}");                                           'vc' => 'Verify Content',
        }                                           'cv' => 'Check/Set Resource Versions',
    }                                           'ls' => 'List Symbs',
 }                                           'sl' => 'Show Log',
                                            'imse' => 'IMS Export',
 function makeims() {                                           'dcd' => 'Dump Course DOCS to Construction Space: available on other servers'
     var caller = document.forms.ims.folder.value;                                            );
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";    my %help = %{$help_ref};
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");    my %env = %{$env_ref};
     newWindow.location.href = newlocation;    my $dumpbut=&dumpbutton();
 }    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'}.'")\' />' 
 function finishpick() {          => "<a onclick='javascript:injectData(document.courseverify, \"dummy\", \"verify\", \"$lt{'vc'}\")'>$lt{'vc'}</a>$help{'Verify_Content'}"},
     var title=this.document.forms.extimport.title.value;   {'<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 url=this.document.forms.extimport.url.value;          =>"<a onclick='javascript:injectData(document.courseverify, \"dummy\", \"versions\", \"$lt{'cv'}\")'>$lt{'cv'}</a>$help{'Check_Resource_Versions'}"},
     var form=this.document.forms.extimport.useform.value;   );
     var residx=this.document.forms.extimport.residx.value;    if($dumpbut ne ''){
     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/dump.png" alt="'.$lt{dcd}.'" />'=>$dumpbut};
 }    }
     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').'")\' />'
 function changename(folderpath,index,oldtitle,container,pagesymb) {            =>$exportbut},
     var title=prompt('$lt{"p_chn"}',oldtitle);   {'<img class="LC_noBorder LC_middle" src="/res/adm/pages/symbs.png" alt="'.$lt{ls}.'"  onclick=\'javascript:injectData(document.courseverify, "dummy", "listsymbs", "'.$lt{'ls'}.'")\'  />'
     if (title) {          =>"<a onclick='javascript:injectData(document.courseverify, \"dummy\", \"listsymbs\", \"$lt{'ls'}\")'>$lt{'ls'}</a><input type='hidden' name='folder' value='$env{'form.folder'}' />"},
  this.document.forms.renameform.markcopy.value=-1;   {'<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.title.value=title;          =>"<a onclick='javascript:injectData(document.courseverify, \"dummy\", \"docslog\", \"$lt{'sl'}\")'>$lt{'sl'}</a>"},
  this.document.forms.renameform.cmd.value='rename_'+index;   );
         if (container == 'sequence') {    return '<form action="/adm/coursedocs" method="post" name="courseverify"><input type="hidden" id="dummy" />'.create_form_ul(create_list_elements(@list)).'</form>';
     this.document.forms.renameform.folderpath.value=folderpath;  
         }  }
         if (container == 'page') {  
             this.document.forms.renameform.pagepath.value=folderpath;  
             this.document.forms.renameform.pagesymb.value=pagesymb;  sub generate_edit_table {
         }      my ($tid,$orderhash_ref) = @_;
         this.document.forms.renameform.submit();      return unless(ref($orderhash_ref) eq 'HASH');
     }      my %orderhash = %{$orderhash_ref};
 }      my $form;
       my $activetab;
 function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {      my $active;
     if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {      if($env{'form.active'} ne ''){
  this.document.forms.renameform.markcopy.value=-1;          $activetab = $env{'form.active'};
  this.document.forms.renameform.cmd.value='del_'+index;      }
         if (container == 'sequence') {      $form = '<div class="LC_Box" style="margin-right:0">';
             this.document.forms.renameform.folderpath.value=folderpath;      $form .= '<ul id="navigation'.$tid.'" class="LC_TabContent">';
         }      foreach my $name (sort(keys(%orderhash))){
         if (container == 'page') {          if($name ne '00'){
             this.document.forms.renameform.pagepath.value=folderpath;              if($activetab eq '' || $activetab ne $name){
             this.document.forms.renameform.pagesymb.value=pagesymb;                 $active = '';
         }              }elsif($activetab eq $name){
         this.document.forms.renameform.submit();                 $active = 'class="active"';
     }              }
 }              $form .= '<li '.$active.' onclick="javascript:showPage(this, \''.$name.$tid.'\', \'navigation'.$tid.'\',\'content'.$tid.'\');">'.&mt(${$orderhash{$name}}[0]).'</li>';
           } else {
 function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {      $form .= '<li '.$active.'>'.${$orderhash{$name}}[1].'</li>';
     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;      $form .= '</ul>';
         if (container == 'sequence') {      $form .= '<div id="content'.$tid.'" style="padding: 0 0; margin: 0 0; clear: both;">';
             this.document.forms.renameform.folderpath.value=folderpath;      foreach my $field (keys(%orderhash)){
         }   if($field ne '00'){
         if (container == 'page') {          if($activetab eq '' || $activetab ne $field){
             this.document.forms.renameform.pagepath.value=folderpath;                  $active = 'style="display: none;"';
             this.document.forms.renameform.pagesymb.value=pagesymb;          }elsif($activetab eq $field){
         }                  $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;      }
     this.document.forms.renameform.copyfolder.value=folder+'.'+container;      $form .= '</div></div>';
     if (container == 'sequence') {  
  this.document.forms.renameform.folderpath.value=folderpath;      return $form;
     }  }
     if (container == 'page') {  
  this.document.forms.renameform.pagepath.value=folderpath;  sub editing_js {
  this.document.forms.renameform.pagesymb.value=pagesymb;      my ($udom,$uname) = @_;
     }      my $now = time();
     this.document.forms.renameform.submit();      my %lt = &Apache::lonlocal::texthash(
 }                                            p_mnf => 'Name of New Folder',
                                             t_mnf => 'New Folder',
                                             p_mnp => 'Name of New Page',
 ENDNEWSCRIPT                                            t_mnp => 'New Page',
 }                                            p_mxu => 'Title for the Uploaded Score',
 1;                                            p_msp => 'Name of Simple Course Page',
 __END__                                            p_msb => 'Title for the Problem',
                                             p_mdb => 'Title for the Drop Box',
                                             p_mbb => 'Title for the Discussion Board',
 =head1 NAME                                            p_mab => "Enter user:domain for User's Personal Information Page",
                                             p_mab2 => 'Personal Information Page of ',
 Apache::londocs.pm                                            p_mab_alrt1 => 'Not a valid user:domain',
                                             p_mab_alrt2 => 'Please enter both user and domain in the format user:domain',
 =head1 SYNOPSIS                                            p_chn => 'New Title',
                                             p_rmr1 => 'WARNING: Removing a resource makes associated grades and scores inaccessible!',
 This is part of the LearningOnline Network with CAPA project                                            p_rmr2a => 'Remove[_99]',
 described at http://www.lon-capa.org.                                            p_rmr2b => '?[_99]',
                                             p_ctr1a => 'WARNING: Cutting a resource makes associated grades and scores inaccessible!',
 =head1 SUBROUTINES                                            p_ctr1b => 'Grades remain inaccessible if resource is pasted into another folder.',
                                             p_ctr2a => 'Cut[_98]',
 =over                                            p_ctr2b => '?[_98]'
                                           );
 =item %help=()  
       return <<ENDNEWSCRIPT;
 Available help topics  function makenewfolder(targetform,folderseq) {
       var foldername=prompt('$lt{"p_mnf"}','$lt{"t_mnf"}');
 =item mapread()      if (foldername) {
          targetform.importdetail.value=escape(foldername)+"="+folderseq;
 Mapread read maps into LONCAPA::map:: global arrays          targetform.submit();
 @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) {
 =item authorhosts()      var pagename=prompt('$lt{"p_mnp"}','$lt{"t_mnp"}');
       if (pagename) {
 Return hash with valid author names          targetform.importdetail.value=escape(pagename)+"="+folderseq;
           targetform.submit();
 =item dumpbutton()      }
   }
 Generate "dump" button  
   function makenewext(targetname) {
 =item clean()      this.document.forms.extimport.useform.value=targetname;
       this.document.forms.extimport.title.value='';
 =item dumpcourse()      this.document.forms.extimport.url.value='';
       this.document.forms.extimport.residx.value='';
     Actually dump course      window.open('/adm/rat/extpickframe.html');
   }
   
 =item exportbutton()  function edittext(targetname,residx,title,url) {
       this.document.forms.extimport.useform.value=targetname;
     Generate "export" button      this.document.forms.extimport.residx.value=residx;
       this.document.forms.extimport.url.value=url;
 =item exportcourse()      this.document.forms.extimport.title.value=title;
       window.open('/adm/rat/extpickframe.html');
 =item create_ims_store()  }
   
 =item build_package()  function makeexamupload() {
      var title=prompt('$lt{"p_mxu"}');
 =item get_dependencies()     if (title) {
       this.document.forms.newexamupload.importdetail.value=
 =item process_content()   escape(title)+'=/res/lib/templates/examupload.problem';
       this.document.forms.newexamupload.submit();
 =item replicate_content()     }
   }
 =item extract_media()  
   function makesmppage() {
 =item store_template()     var title=prompt('$lt{"p_msp"}');
      if (title) {
 =item group_import()      this.document.forms.newsmppg.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/smppg';
     Imports the given (name, url) resources into the course      this.document.forms.newsmppg.submit();
     coursenum, coursedom, and folder must precede the list     }
   }
 =item breadcrumbs()  
   function makesmpproblem() {
 =item log_docs()     var title=prompt('$lt{"p_msb"}');
      if (title) {
 =item docs_change_log()      this.document.forms.newsmpproblem.importdetail.value=
    escape(title)+'=/res/lib/templates/simpleproblem.problem';
 =item update_paste_buffer()      this.document.forms.newsmpproblem.submit();
      }
 =item print_paste_buffer()  }
   
 =item do_paste_from_buffer()  function makedropbox() {
      var title=prompt('$lt{"p_mdb"}');
 =item update_parameter()     if (title) {
       this.document.forms.newdropbox.importdetail.value=
 =item handle_edit_cmd()          escape(title)+'=/res/lib/templates/DropBox.problem';
       this.document.forms.newdropbox.submit();
 =item editor()     }
   }
 =item process_file_upload()  
   function makebulboard() {
 =item process_secondary_uploads()     var title=prompt('$lt{"p_mbb"}');
      if (title) {
 =item is_supplemental_title()      this.document.forms.newbul.importdetail.value=
    escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';
 =item parse_supplemental_title()      this.document.forms.newbul.submit();
      }
 =item entryline()  }
   
 =item tiehash()  function makeabout() {
      var user=prompt("$lt{'p_mab'}");
 =item untiehash()     if (user) {
          var comp=new Array();
 =item checkonthis()         comp=user.split(':');
          if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {
 check on this     if ((comp[0]) && (comp[1])) {
          this.document.forms.newaboutsomeone.importdetail.value=
 =item verifycontent()     '$lt{"p_mab2"}'+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';
          this.document.forms.newaboutsomeone.submit();
 Verify Content     } else {
          alert("$lt{'p_mab_alrt1'}");
 =item devalidateversioncache() & checkversions()     }
   } else {
 Check Versions     alert("$lt{'p_mab_alrt2'}");
   }
 =item mark_hash_old()  }
   }
 =item is_hash_old()  
   function makeims() {
 =item changewarning()  var caller = document.forms.ims.folder.value;
   var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";
 =item init_breadcrumbs()  newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");
   newWindow.location.href = newlocation;
 Breadcrumbs for special functions  }
   
 =back  
   function finishpick() {
 =cut  var title=this.document.forms.extimport.title.value;
   var url=this.document.forms.extimport.url.value;
   var form=this.document.forms.extimport.useform.value;
   var residx=this.document.forms.extimport.residx.value;
   eval('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+'='+residx+'";this.document.forms.'+form+'.submit();');
   }
   
   function changename(folderpath,index,oldtitle,container,pagesymb) {
   var title=prompt('$lt{"p_chn"}',oldtitle);
   if (title) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.title.value=title;
   this.document.forms.renameform.cmd.value='rename_'+index;
   if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
       this.document.forms.renameform.pagepath.value=folderpath;
       this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   }
   
   function removeres(folderpath,index,oldtitle,container,pagesymb,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_rmr1"}\\n\\n$lt{"p_rmr2a"} "'+oldtitle+'" $lt{"p_rmr2b"}')) {
   this.document.forms.renameform.markcopy.value=-1;
   this.document.forms.renameform.cmd.value='del_'+index;
   if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
       this.document.forms.renameform.pagepath.value=folderpath;
       this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   }
   
   function cutres(folderpath,index,oldtitle,container,pagesymb,folder,skip_confirm) {
   if (skip_confirm || confirm('$lt{"p_ctr1a"}\\n$lt{"p_ctr1b"}\\n\\n$lt{"p_ctr2a"} "'+oldtitle+'" $lt{"p_ctr2b"}')) {
   this.document.forms.renameform.cmd.value='cut_'+index;
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   if (container == 'sequence') {
       this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
       this.document.forms.renameform.pagepath.value=folderpath;
       this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   }
   
   function markcopy(folderpath,index,oldtitle,container,pagesymb,folder) {
   this.document.forms.renameform.markcopy.value=index;
   this.document.forms.renameform.copyfolder.value=folder+'.'+container;
   if (container == 'sequence') {
   this.document.forms.renameform.folderpath.value=folderpath;
   }
   if (container == 'page') {
   this.document.forms.renameform.pagepath.value=folderpath;
   this.document.forms.renameform.pagesymb.value=pagesymb;
   }
   this.document.forms.renameform.submit();
   }
   
   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.418


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