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

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


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