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

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


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