Diff for /loncom/interface/londocs.pm between versions 1.328 and 1.411.2.1

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

Removed from v.1.328  
changed lines
  Added in v.1.411.2.1


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