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

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

Removed from v.1.327  
changed lines
  Added in v.1.418


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