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

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


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