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

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


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