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

version 1.275, 2007/06/11 21:27:23 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 = shift;              my $storetemplate;
     my $coursedom = shift;              if ($storetemplate = Apache::File->new('>'.$destination)) {
     my $folder = shift;                  print $storetemplate $contents;
     my $container = shift;                  close($storetemplate);
     my $caller = shift;              }
     while (@_) {              if ($content_type eq 'external') {
  my $name = shift;                  return 'resources/'.$count.'/'.$content_type.'.html';
  my $url = shift;              } else {
         if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$}) && ($caller eq 'londocs')) {                  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".  
                             '</map>';  sub group_import {
             $env{'form.output'}=$newmapstr;      my ($coursenum, $coursedom, $folder, $container, $caller, @files) = @_;
             my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,  
                                                 'output',$1.$2);      while (@files) {
             if ($result != m|^/uploaded/|) {   my ($name, $url, $residx) = @{ shift(@files) };
                 $errtext.='Map not saved: A network error occured when trying to save the new map. ';          if (($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/(default_\d+\.)(page|sequence)$})
                 $fatal = 2;       && ($caller eq 'londocs')
             }       && (!&Apache::lonnet::stat_file($url))) {
             if ($fatal) {      
                 return ($errtext,$fatal);              my $errtext = '';
             }              my $fatal = 0;
         }              my $newmapstr = '<map>'."\n".
  if ($url) {                              '<resource id="1" src="" type="start"></resource>'."\n".
     my $idx = &LONCAPA::map::getresidx($url);                              '<link from="1" to="2" index="1"></link>'."\n".
     $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;                              '<resource id="2" src="" type="finish"></resource>'."\n".
     my $ext = 'false';                              '</map>';
     if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }              $env{'form.output'}=$newmapstr;
     $url  = &LONCAPA::map::qtunescape($url);              my $result=&Apache::lonnet::finishuserfileupload($coursenum,$coursedom,
     $name = &LONCAPA::map::qtunescape($name);                                                  'output',$1.$2);
     $LONCAPA::map::resources[$idx] =               if ($result != m|^/uploaded/|) {
  join ':', ($name, $url, $ext, 'normal', 'res');                  $errtext.='Map not saved: A network error occurred when trying to save the new map. ';
  }                  $fatal = 2;
     }              }
     return &storemap($coursenum, $coursedom, $folder.'.'.$container);              if ($fatal) {
 }                  return ($errtext,$fatal);
               }
 sub breadcrumbs {          }
     my ($where)=@_;   if ($url) {
     &Apache::lonhtmlcommon::clear_breadcrumbs();      if (!$residx
     my (@folders);   || defined($LONCAPA::map::zombies[$residx])) {
     if ($env{'form.pagepath'}) {   $residx = &LONCAPA::map::getresidx($url,$residx);
         @folders = split('&',$env{'form.pagepath'});   push(@LONCAPA::map::order, $residx);
     } else {      }
         @folders=split('&',$env{'form.folderpath'});      my $ext = 'false';
     }      if ($url=~m{^http://} || $url=~m{^https://}) { $ext = 'true'; }
     my $folderpath;      $url  = &LONCAPA::map::qtunescape($url);
     my $cpinfo='';      $name = &LONCAPA::map::qtunescape($name);
     my $plain='';      $LONCAPA::map::resources[$residx] =
     if ($env{'form.markedcopy_url'}) {   join(':', ($name, $url, $ext, 'normal', 'res'));
        $cpinfo='&markedcopy_url='.   }
                &escape($env{'form.markedcopy_url'}).      }
                '&markedcopy_title='.      return &storemap($coursenum, $coursedom, $folder.'.'.$container);
                &escape($env{'form.markedcopy_title'});  }
     }  
     my $randompick=-1;  sub breadcrumbs {
     my $isencrypted=0;      my ($where,$allowed,$type)=@_;
     my $ishidden=0;      &Apache::lonhtmlcommon::clear_breadcrumbs();
     while (@folders) {      my (@folders);
  my $folder=shift(@folders);      if ($env{'form.pagepath'}) {
  my $foldername=shift(@folders);          @folders = split('&',$env{'form.pagepath'});
  if ($folderpath) {$folderpath.='&';}      } else {
  $folderpath.=$folder.'&'.$foldername;          @folders=split('&',$env{'form.folderpath'});
  my $url='/adm/coursedocs?folderpath='.      }
     &escape($folderpath);      my $folderpath;
             my $name=&unescape($foldername);      my $cpinfo='';
 # randompick number, hidden, encrypted is appended with ":"s to the foldername      my $plain='';
             $name=~s/\:(\d*)\:(\w*)\:(\w*)$//;      my $randompick=-1;
             if ($1 ne '') {       my $isencrypted=0;
                $randompick=$1;      my $ishidden=0;
             } else {      my $is_random_order=0;
                $randompick=-1;      while (@folders) {
             }   my $folder=shift(@folders);
             if ($2) { $ishidden=1; }      my $foldername=shift(@folders);
             if ($3) { $isencrypted=1; }   if ($folderpath) {$folderpath.='&';}
     &Apache::lonhtmlcommon::add_breadcrumb(   $folderpath.=$folder.'&'.$foldername;
       {'href'=>$url.$cpinfo,   my $url='/adm/coursedocs?folderpath='.
        'title'=>$name,      &escape($folderpath);
        'text'=>'<font size="+1">'.      my $name=&unescape($foldername);
    $name.'</font>',  # randompick number, hidden, encrypted, random order, is appended with ":"s to the foldername
        'no_mt'=>1,       $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)$//;
        });      if ($1 ne '') {
  $plain.=$name.' &gt; ';                 $randompick=$1;
     }              } else {
     $plain=~s/\&gt\;\s*$//;                 $randompick=-1;
     return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',              }
        'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain);              if ($2) { $ishidden=1; }
 }              if ($3) { $isencrypted=1; }
       if ($4 ne '') { $is_random_order = 1; }
 sub log_docs {              if ($folder eq 'supplemental') {
     return &Apache::lonnet::instructor_log('docslog',@_);                  if ($allowed) {
 }                      $name = &mt('Supplemental '.$type.' Documents');
                   } else {
 {                      $name = &mt($type.' Documents');
     my @oldresources=();                  }
     my @oldorder=();              }
     my $parmidx;      &Apache::lonhtmlcommon::add_breadcrumb(
     my %parmaction=();        {'href'=>$url.$cpinfo,
     my %parmvalue=();         'title'=>$name,
     my $changedflag;         'text'=>'<font size="+1">'.
      $name.'</font>',
     sub snapshotbefore {         'no_mt'=>1,
         @oldresources=@LONCAPA::map::resources;         });
         @oldorder=@LONCAPA::map::order;   $plain.=$name.' &gt; ';
         $parmidx=undef;      }
         %parmaction=();      $plain=~s/\&gt\;\s*$//;
         %parmvalue=();      return (&Apache::lonhtmlcommon::breadcrumbs(undef,undef,0,'nohelp',
         $changedflag=0;         'LC_docs_path'),$randompick,$ishidden,$isencrypted,$plain,$is_random_order);
     }  }
   
     sub remember_parms {  sub log_docs {
         my ($idx,$parameter,$action,$value)=@_;      return &Apache::lonnet::instructor_log('docslog',@_);
         $parmidx=$idx;  }
         $parmaction{$parameter}=$action;  
         $parmvalue{$parameter}=$value;  {
         $changedflag=1;      my @oldresources=();
     }      my @oldorder=();
       my $parmidx;
     sub log_differences {      my %parmaction=();
         my ($plain)=@_;      my %parmvalue=();
         my %storehash=('folder' => $plain,      my $changedflag;
                        'currentfolder' => $env{'form.folder'});  
         if ($parmidx) {      sub snapshotbefore {
            $storehash{'parameter_res'}=$oldresources[$parmidx];          @oldresources=@LONCAPA::map::resources;
            foreach my $parm (keys %parmaction) {          @oldorder=@LONCAPA::map::order;
               $storehash{'parameter_action_'.$parm}=$parmaction{$parm};          $parmidx=undef;
               $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};          %parmaction=();
            }          %parmvalue=();
         }          $changedflag=0;
         my $maxidx=$#oldresources;      }
         if ($#LONCAPA::map::resources>$#oldresources) {  
            $maxidx=$#LONCAPA::map::resources;      sub remember_parms {
         }          my ($idx,$parameter,$action,$value)=@_;
         for (my $idx=0; $idx<=$maxidx; $idx++) {          $parmidx=$idx;
            if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {          $parmaction{$parameter}=$action;
               $storehash{'before_resources_'.$idx}=$oldresources[$idx];          $parmvalue{$parameter}=$value;
               $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];          $changedflag=1;
               $changedflag=1;      }
            }  
            if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {      sub log_differences {
               $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];          my ($plain)=@_;
               $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];          my %storehash=('folder' => $plain,
               $changedflag=1;                         'currentfolder' => $env{'form.folder'});
            }          if ($parmidx) {
         }             $storehash{'parameter_res'}=$oldresources[$parmidx];
  $storehash{'maxidx'}=$maxidx;             foreach my $parm (keys(%parmaction)) {
         if ($changedflag) { &log_docs(\%storehash); }                $storehash{'parameter_action_'.$parm}=$parmaction{$parm};
     }                $storehash{'parameter_value_'.$parm}=$parmvalue{$parm};
 }             }
           }
           my $maxidx=$#oldresources;
 #          if ($#LONCAPA::map::resources>$#oldresources) {
 # Docs Change Log             $maxidx=$#LONCAPA::map::resources;
 #          }
 sub docs_change_log {          for (my $idx=0; $idx<=$maxidx; $idx++) {
     my ($r)=@_;             if ($LONCAPA::map::resources[$idx] ne $oldresources[$idx]) {
     my $folder=$env{'form.folder'};                $storehash{'before_resources_'.$idx}=$oldresources[$idx];
     $r->print(&Apache::loncommon::start_page('Course Document Change Log'));                $storehash{'after_resources_'.$idx}=$LONCAPA::map::resources[$idx];
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));                $changedflag=1;
     my %docslog=&Apache::lonnet::dump('nohist_docslog',             }
                                       $env{'course.'.$env{'request.course.id'}.'.domain'},             if ($LONCAPA::map::order[$idx] ne $oldorder[$idx]) {
                                       $env{'course.'.$env{'request.course.id'}.'.num'});                $storehash{'before_order_res_'.$idx}=$oldresources[$oldorder[$idx]];
                 $storehash{'after_order_res_'.$idx}=$LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }                $changedflag=1;
              }
     $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.          }
               '<input type="hidden" name="docslog" value="1" />');   $storehash{'maxidx'}=$maxidx;
           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',  
     'encrypturl'     => 'URL hidden',  sub docs_change_log {
     'randompick'     => 'Randomly pick',      my ($r)=@_;
     'set'            => 'set to',      my $folder=$env{'form.folder'};
     'del'            => 'deleted');      $r->print(&Apache::loncommon::start_page('Course Document Change Log'));
     $r->print(&Apache::loncommon::display_filter().      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Document Change Log'));
               '<input type="hidden" name="folder" value="'.$folder.'" />'.      my %docslog=&Apache::lonnet::dump('nohist_docslog',
               '<input type="submit" value="'.&mt('Display').'" /></form>');                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
     $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().                                        $env{'course.'.$env{'request.course.id'}.'.num'});
               '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.  
               &mt('After').'</th>'.      if ((keys(%docslog))[0]=~/^error\:/) { undef(%docslog); }
               &Apache::loncommon::end_data_table_header_row());  
     my $shown=0;      $r->print('<form action="/adm/coursedocs" method="post" name="docslog">'.
     foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {                '<input type="hidden" name="docslog" value="1" />');
  if ($env{'form.displayfilter'} eq 'currentfolder') {  
     if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }      my %saveable_parameters = ('show' => 'scalar',);
  }      &Apache::loncommon::store_course_settings('docs_log',
         my @changes=keys(%{$docslog{$id}{'logentry'}});                                                \%saveable_parameters);
         if ($env{'form.displayfilter'} eq 'containing') {      &Apache::loncommon::restore_course_settings('docs_log',
     my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.                                                  \%saveable_parameters);
  &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});      if (!$env{'form.show'}) { $env{'form.show'}=10; }
     foreach my $key (@changes) {      my %lt=('hiddenresource' => 'Resources hidden',
  $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};      'encrypturl'     => 'URL hidden',
     }      'randompick'     => 'Randomly pick',
     if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }               'randomorder'    => 'Randomly ordered',
  }      'set'            => 'set to',
         my $count = 0;      'del'            => 'deleted');
         my $time =      $r->print(&Apache::loncommon::display_filter().
             &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});                '<input type="hidden" name="folder" value="'.$folder.'" />'.
         my $plainname =                '<input type="submit" value="'.&mt('Display').'" /></form>');
             &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},      $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
                                           $docslog{$id}{'exe_udom'});                '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Folder').'</th><th>'.&mt('Before').'</th><th>'.
         my $about_me_link =                &mt('After').'</th>'.
             &Apache::loncommon::aboutmewrapper($plainname,                &Apache::loncommon::end_data_table_header_row());
                                                $docslog{$id}{'exe_uname'},      my $shown=0;
                                                $docslog{$id}{'exe_udom'});      foreach my $id (sort { $docslog{$b}{'exe_time'}<=>$docslog{$a}{'exe_time'} } (keys(%docslog))) {
         my $send_msg_link='';   if ($env{'form.displayfilter'} eq 'currentfolder') {
         if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})      if ($docslog{$id}{'logentry'}{'currentfolder'} ne $folder) { next; }
              || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {   }
             $send_msg_link ='<br />'.          my @changes=keys(%{$docslog{$id}{'logentry'}});
                 &Apache::loncommon::messagewrapper(&mt('Send message'),          if ($env{'form.displayfilter'} eq 'containing') {
                                                    $docslog{$id}{'exe_uname'},      my $wholeentry=$docslog{$id}{'exe_uname'}.':'.$docslog{$id}{'exe_udom'}.':'.
                                                    $docslog{$id}{'exe_udom'});   &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},$docslog{$id}{'exe_udom'});
         }      foreach my $key (@changes) {
         $r->print(&Apache::loncommon::start_data_table_row());   $wholeentry.=':'.$docslog{$id}{'logentry'}{$key};
         $r->print('<td>'.$time.'</td>      }
                        <td>'.$about_me_link.      if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }        
                   '<br /><tt>'.$docslog{$id}{'exe_uname'}.   }
                                   ':'.$docslog{$id}{'exe_udom'}.'</tt>'.          my $count = 0;
                   $send_msg_link.'</td><td>'.          my $time =
                   $docslog{$id}{'logentry'}{'folder'}.'</td><td>');              &Apache::lonlocal::locallocaltime($docslog{$id}{'exe_time'});
 # Before          my $plainname =
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {              &Apache::loncommon::plainname($docslog{$id}{'exe_uname'},
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                                            $docslog{$id}{'exe_udom'});
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];          my $about_me_link =
     if ($oldname ne $newname) {              &Apache::loncommon::aboutmewrapper($plainname,
  $r->print(&LONCAPA::map::qtescape($oldname));                                                 $docslog{$id}{'exe_uname'},
     }                                                 $docslog{$id}{'exe_udom'});
  }          my $send_msg_link='';
  $r->print('<ul>');          if ((($docslog{$id}{'exe_uname'} ne $env{'user.name'})
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {               || ($docslog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
             if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {              $send_msg_link ='<br />'.
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');                  &Apache::loncommon::messagewrapper(&mt('Send message'),
     }                                                     $docslog{$id}{'exe_uname'},
  }                                                     $docslog{$id}{'exe_udom'});
  $r->print('</ul>');          }
 # After          $r->print(&Apache::loncommon::start_data_table_row());
         $r->print('</td><td>');          $r->print('<td>'.$time.'</td>
                          <td>'.$about_me_link.
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {                    '<br /><tt>'.$docslog{$id}{'exe_uname'}.
     my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];                                    ':'.$docslog{$id}{'exe_udom'}.'</tt>'.
     my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];                    $send_msg_link.'</td><td>'.
     if ($oldname ne $newname) {                    $docslog{$id}{'logentry'}{'folder'}.'</td><td>');
  $r->print(&LONCAPA::map::qtescape($newname));  # Before
     }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  }              my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
  $r->print('<ul>');      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
  for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {      if ($oldname ne $newname) {
             if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {   $r->print(&LONCAPA::map::qtescape($oldname));
  $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');      }
     }   }
  }   $r->print('<ul>');
  $r->print('</ul>');   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
  if ($docslog{$id}{'logentry'}{'parameter_res'}) {              if ($docslog{$id}{'logentry'}{'before_order_res_'.$idx}) {
     $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'before_order_res_'.$idx}))[0]).'</li>');
     foreach my $parameter ('randompick','hiddenresource','encrypturl') {      }
  if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {   }
     $r->print('<li>'.   $r->print('</ul>');
       &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',  # After
   $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})          $r->print('</td><td>');
       .'</li>');  
  }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     }      my $oldname=(split(/\:/,$docslog{$id}{'logentry'}{'before_resources_'.$idx}))[0];
     $r->print('</ul>');      my $newname=(split(/\:/,$docslog{$id}{'logentry'}{'after_resources_'.$idx}))[0];
  }      if ($oldname ne '' && $oldname ne $newname) {
 # End   $r->print(&LONCAPA::map::qtescape($newname));
         $r->print('</td>'.&Apache::loncommon::end_data_table_row());      }
         $shown++;   }        
         if (!($env{'form.show'} eq &mt('all')   $r->print('<ul>');
               || $shown<=$env{'form.show'})) { last; }   for (my $idx=0;$idx<=$docslog{$id}{'logentry'}{'maxidx'};$idx++) {
     }              if ($docslog{$id}{'logentry'}{'after_order_res_'.$idx}) {
     $r->print(&Apache::loncommon::end_data_table());   $r->print('<li>'.&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'after_order_res_'.$idx}))[0]).'</li>');
     $r->print(&Apache::loncommon::end_page());      }
 }   }
    $r->print('</ul>');
 sub editor {   if ($docslog{$id}{'logentry'}{'parameter_res'}) {
     my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output)=@_;      $r->print(&LONCAPA::map::qtescape((split(/\:/,$docslog{$id}{'logentry'}{'parameter_res'}))[0]).':<ul>');
     my $errtext='';      foreach my $parameter ('randompick','hiddenresource','encrypturl','randomorder') {
     my $fatal=0;   if ($docslog{$id}{'logentry'}{'parameter_action_'.$parameter}) {
     my $container='sequence';      $r->print('<li>'.
     if ($env{'form.pagepath'}) {        &mt($lt{$parameter}.' '.$lt{$docslog{$id}{'logentry'}{'parameter_action_'.$parameter}}.' [_1]',
         $container='page';    $docslog{$id}{'logentry'}{'parameter_value_'.$parameter})
     }        .'</li>');
     ($errtext,$fatal)=   }
               &mapread($coursenum,$coursedom,$folder.'.'.$container);      }
     if ($#LONCAPA::map::order<1) {      $r->print('</ul>');
  my $idx=&LONCAPA::map::getresidx();   }
  if ($idx<=0) { $idx=1; }  # End
         $LONCAPA::map::order[0]=$idx;          $r->print('</td>'.&Apache::loncommon::end_data_table_row());
         $LONCAPA::map::resources[$idx]='';          $shown++;
     }          if (!($env{'form.show'} eq &mt('all')
     if (defined($env{'form.markcopy'})) {                || $shown<=$env{'form.show'})) { last; }
 # Mark for copying      }
  my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);      $r->print(&Apache::loncommon::end_data_table());
  $env{'form.markedcopy_title'}=$title;  }
  $env{'form.markedcopy_url'}=$url;  
     }  sub update_paste_buffer {
     my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain)=&breadcrumbs($folder);      my ($coursenum,$coursedom) = @_;
     $r->print($breadcrumbtrail);  
     if ($fatal) {      return if (!defined($env{'form.markcopy'}));
    $r->print('<p><font color="red">'.$errtext.'</font></p>');      return if (!defined($env{'form.copyfolder'}));
     } else {      return if ($env{'form.markcopy'} < 0);
 # ------------------------------------------------------------ Process commands  
       my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 # ---------------- if they are for this folder and user allowed to make changes      $env{'form.copyfolder'});
  if (($allowed) && ($env{'form.folder'} eq $folder)) {     
 # set parameters and change order      return if ($fatal);
             &snapshotbefore();  
     if ($env{'form.changeparms'}) {  # Mark for copying
  my $idx=$env{'form.setparms'};      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
 # set parameters      if (&is_supplemental_title($title)) {
  if ($env{'form.changeparms'} eq 'randompick') {          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
     if ($env{'form.randpick_'.$idx}) {   ($title) = &parse_supplemental_title($title);
  &LONCAPA::map::storeparameter($idx,'parameter_randompick',$env{'form.randpick_'.$idx},'int_pos');      } elsif ($env{'docs.markedcopy_supplemental'}) {
  &remember_parms($idx,'randompick','set',$env{'form.randpick_'.$idx});          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
     } else {      }
  &LONCAPA::map::delparameter($idx,'parameter_randompick');      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
  &remember_parms($idx,'randompick','del');  
     }      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
  }      'docs.markedcopy_url'   => $url});
  if ($env{'form.changeparms'} eq 'hiddenresource') {      delete($env{'form.markcopy'});
     if ($env{'form.hidprs_'.$idx}) {  }
  &LONCAPA::map::storeparameter($idx,'parameter_hiddenresource','yes','string_yesno');  
  &remember_parms($idx,'hiddenresource','set',$env{'form.hidprs_'.$idx});  sub print_paste_buffer {
     } else {      my ($r,$container) = @_;
  &LONCAPA::map::delparameter($idx,'parameter_hiddenresource');      return if (!defined($env{'docs.markedcopy_url'}));
  &remember_parms($idx,'hiddenresource','del');  
     }      $r->print(<<ENDPASTE);
  }  <form name="pasteform" action="/adm/coursedocs" method="post"><p>
  if ($env{'form.changeparms'} eq 'encrypturl') {  ENDPASTE
     if ($env{'form.encprs_'.$idx}) {      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
  &LONCAPA::map::storeparameter($idx,'parameter_encrypturl','yes','string_yesno');  
  &remember_parms($idx,'encrypturl','set',$env{'form.encprs_'.$idx});      my $type;
     } else {      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
  &LONCAPA::map::delparameter($idx,'parameter_encrypturl');   $type = &mt('External Resource');
  &remember_parms($idx,'encrypturl','del');   $r->print($type.': '.
     }    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
  }    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
 # store the changed version      }  else {
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
  if ($fatal) {   my $icon = &Apache::loncommon::icon($extension);
     $r->print('<p><font color="red">'.$errtext.'</font></p>');   if ($extension eq 'sequence' &&
     return;      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
  }      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     }      $icon .= '/folder_closed.gif';
    }
     if ($env{'form.newpos'}) {   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
 # change order   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
  my $newpos=$env{'form.newpos'}-1;      }
  my $currentpos=$env{'form.currentpos'}-1;      if ($container eq 'page') {
  my $i;   $r->print('
  my @neworder=();   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
  if ($newpos>$currentpos) {   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
 # moving stuff up  ');
     for ($i=0;$i<$currentpos;$i++) {      } else {
  $neworder[$i]=$LONCAPA::map::order[$i];   $r->print('
     }          <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++) {  
  $neworder[$i]=$LONCAPA::map::order[$i];  sub do_paste_from_buffer {
     }      my ($coursenum,$coursedom,$folder) = @_;
  } else {  
 # moving stuff down      if (!$env{'form.pastemarked'}) {
     for ($i=0;$i<$newpos;$i++) {          return;
  $neworder[$i]=$LONCAPA::map::order[$i];      }
     }  
     $neworder[$newpos]=$LONCAPA::map::order[$currentpos];  # paste resource to end of list
     for ($i=$newpos+1;$i<$currentpos+1;$i++) {      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
  $neworder[$i]=$LONCAPA::map::order[$i-1];      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
     }  # Maps need to be copied first
     for ($i=$currentpos+1;$i<=$#LONCAPA::map::order;$i++) {      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
  $neworder[$i]=$LONCAPA::map::order[$i];   $title=&mt('Copy of').' '.$title;
     }   my $newid=$$.int(rand(100)).time;
  }   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
  @LONCAPA::map::order=@neworder;          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
 # store the changed version              my $path = $1;
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);              my $prefix = $2;
  if ($fatal) {              my $ancestor = $3;
     $r->print('<p><font color="red">'.$errtext.'</font></p>');              if (length($ancestor) > 10) {
     return;                  $ancestor = substr($ancestor,-10,10);
  }              }
     }              $oldid = $path.$prefix.$ancestor;
           }
     if ($env{'form.pastemarked'}) {          my $counter = 0;
 # paste resource to end of list          my $newurl=$oldid.$newid.'.'.$ext;
                 my $url=$env{'form.markedcopy_url'};          my $is_unique = &uniqueness_check($newurl);
  my $title=$env{'form.markedcopy_title'};          while (!$is_unique && $counter < 100) {
 # Maps need to be copied first              $counter ++;
  if (($url=~/\.(page|sequence)$/) || ($url=~/^\/uploaded\//)) {              $newid ++;
     $title=&mt('Copy of').' '.$title;              $newurl = $oldid.$newid;
                     my $newid=$$.time;              $is_unique = &uniqueness_check($newurl);
     $url=~/^(.+)\.(\w+)$/;          }
     my $newurl=$1.$newid.'.'.$2;          if (!$is_unique) {
     my $storefn=$newurl;              if ($url=~/\.page$/) {
                     $storefn=~s{^/\w+/$match_domain/$match_username/}{};                  return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
     &Apache::lonclonecourse::writefile              } else {
  ($env{'request.course.id'},$storefn,                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
  &Apache::lonnet::getfile($url));              }
     $url=$newurl;          }
  }   my $storefn=$newurl;
  $title = &LONCAPA::map::qtunescape($title);   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
  my $ext='false';   my $paste_map_result =
  if ($url=~/^http\:\/\//) { $ext='true'; }              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
  $url   = &LONCAPA::map::qtunescape($url);         &Apache::lonnet::getfile($url));
 # Now insert the URL at the bottom          if ($paste_map_result eq '/adm/notfound.html') {
                 my $newidx=&LONCAPA::map::getresidx($url);              if ($url=~/\.page$/) {
  $LONCAPA::map::resources[$newidx]=                  return &mt('Paste failed: an error occurred saving the composite page');
     $title.':'.$url.':'.$ext.':normal:res';              } else {
  $LONCAPA::map::order[1+$#LONCAPA::map::order]=$newidx;                  return &mt('Paste failed: an error occurred saving the folder');
 # Store the result              }
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);          }
  if ($fatal) {   $url = $newurl;
     $r->print('<p><font color="red">'.$errtext.'</font></p>');      }
     return;  # published maps can only exists once, so remove it from paste buffer when done
  }      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
    &Apache::lonnet::delenv('docs\\.markedcopy');
     }      }
             $r->print($upload_output);      if ($url=~ m{/smppg$}) {
     if ($env{'form.cmd'}) {   my $db_name = &Apache::lonsimplepage::get_db_name($url);
                 my ($cmd,$idx)=split(/\_/,$env{'form.cmd'});   if ($db_name =~ /^smppage_/) {
                 if ($cmd eq 'del') {      #simple pages, need to copy the db contents to a new one.
     my (undef,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$idx]]);      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
     if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&      my $now = time();
  ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {      $db_name =~ s{_\d*$ }{_$now}x;
  &Apache::lonnet::removeuploadedurl($url);      my $result=&Apache::lonnet::put($db_name,\%contents,
     } else {      $coursedom,$coursenum);
  &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
     }      $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);
                     $#LONCAPA::map::order--;      my $ext='false';
                 } elsif ($cmd eq 'cut') {      if ($url=~m{^http(|s)://}) { $ext='true'; }
     my (undef,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$idx]]);      $url       = &LONCAPA::map::qtunescape($url);
     &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);  # Now insert the URL at the bottom
     for (my $i=$idx;$i<$#LONCAPA::map::order;$i++) {      my $newidx = &LONCAPA::map::getresidx($url);
                         $LONCAPA::map::order[$i] = $LONCAPA::map::order[$i+1];      if ($env{'docs.markedcopy_supplemental'}) {
                     }          if ($folder =~ /^supplemental/) {
                     $#LONCAPA::map::order--;              $title = $env{'docs.markedcopy_supplemental'};
                 } elsif ($cmd eq 'up') {          } else {
   if (($idx) && (defined($LONCAPA::map::order[$idx-1]))) {              (undef,undef,$title) =
                     my $i=$LONCAPA::map::order[$idx-1];                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
                     $LONCAPA::map::order[$idx-1] = $LONCAPA::map::order[$idx];          }
                     $LONCAPA::map::order[$idx] = $i;      } else {
    }          if ($folder=~/^supplemental/) {
                 } elsif ($cmd eq 'down') {             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
    if (defined($LONCAPA::map::order[$idx+1])) {                    $env{'user.domain'}.'___&&&___'.$title;
                     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';
                 } elsif ($cmd eq 'rename') {      push(@LONCAPA::map::order, $newidx);
                     my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];      return 'ok';
                     my ($rtitle,@rrest)=split(/\:/,  # Store the result
                        $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]);  }
                     my $comment=$env{'form.title'};  
                     $comment = &LONCAPA::map::qtunescape($comment);  sub uniqueness_check {
     if ($comment=~/\S/) {      my ($newurl) = @_;
  $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=      my $unique = 1;
     $comment.':'.join(':',@rrest);      foreach my $res (@LONCAPA::map::order) {
     }          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
 # Devalidate title cache          $url=&LONCAPA::map::qtescape($url);
                     my $renamed_url=&LONCAPA::map::qtescape($rrest[0]);          if ($newurl eq $url) {
     &Apache::lonnet::devalidate_title_cache($renamed_url);              $unique = 0;
                 }              last;    
 # Store the changed version          }
  ($errtext,$fatal)=&storemap($coursenum,$coursedom,      }
     $folder.'.'.$container);      return $unique;
  if ($fatal) {  }
     $r->print('<p><font color="red">'.$errtext.'</font></p>');  
     return;  my %parameter_type = ( 'randompick'     => 'int_pos',
  }         'hiddenresource' => 'string_yesno',
             }         'encrypturl'     => 'string_yesno',
 # Group import/search         'randomorder'    => 'string_yesno',);
     if ($env{'form.importdetail'}) {  my $valid_parameters_re = join('|',keys(%parameter_type));
  my @imports;  # set parameters
 # &Apache::lonnet::logthis("imp detail ".$env{'form.importdetail'});  sub update_parameter {
  foreach (split(/\&/,$env{'form.importdetail'})) {  
     if (defined($_)) {      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
  my ($name,$url)=split(/\=/,$_);  
  $name=&unescape($name);      my $which = $env{'form.changeparms'};
  $url=&unescape($url);      my $idx = $env{'form.setparms'};
  push @imports, $name, $url;      if ($env{'form.'.$which.'_'.$idx}) {
     }   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
  }                                       : 'yes';
 # Store the changed version   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
  ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,        $parameter_type{$which});
        $container,'londocs',@imports);   &remember_parms($idx,$which,'set',$value);
  if ($fatal) {      } else {
     $r->print('<p><font color="red">'.$errtext.'</font></p>');   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
     return;  
  }   &remember_parms($idx,$which,'del');
             }      }
 # Loading a complete map      return 1;
    if ($env{'form.loadmap'}) {  }
                if ($env{'form.importmap'}=~/\w/) {  
           foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {  
       my ($title,$url,$ext,$type)=split(/\:/,$_);  sub handle_edit_cmd {
                       my $idx=&LONCAPA::map::getresidx($url);      my ($coursenum,$coursedom) =@_;
                       $LONCAPA::map::resources[$idx]=$_;  
                       $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;      my ($cmd,$idx)=split('_',$env{'form.cmd'});
           }  
 # Store the changed version      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
            ($errtext,$fatal)=&storemap($coursenum,$coursedom,      my ($title, $url, @rrest) = split(':', $ratstr);
    $folder.'.'.$container);  
           if ($fatal) {      if ($cmd eq 'del') {
       $r->print('<p><font color="red">'.$errtext.'</font></p>');   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
       return;      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
           }      &Apache::lonnet::removeuploadedurl($url);
                } else {   } else {
                    $r->print('<p><font color="red">'.&mt('No map selected.').'</font></p>');      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
                }   }
            }   splice(@LONCAPA::map::order, $idx, 1);
            &log_differences($plain);  
        }      } elsif ($cmd eq 'cut') {
 # ---------------------------------------------------------------- End commands   &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
 # ---------------------------------------------------------------- Print screen   splice(@LONCAPA::map::order, $idx, 1);
         my $idx=0;  
  my $shown=0;      } elsif ($cmd eq 'up'
         if (($ishidden) || ($isencrypted) || ($randompick>=0)) {       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
            $r->print('<p>'.&mt('Parameters').':<ul>'.   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
                      ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').  
                      ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').      } elsif ($cmd eq 'down'
                      ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').       && defined($LONCAPA::map::order[$idx+1])) {
                      '</ul></p>');   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
         }                                                                                                       
         if ($randompick>=0) {      } elsif ($cmd eq 'rename') {
            $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'});
         $r->print('<table>');   if ($comment=~/\S/) {
         foreach (@LONCAPA::map::order) {      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
            my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$_]);   $comment.':'.join(':', $url, @rrest);
    $name=&LONCAPA::map::qtescape($name);   }
    $url=&LONCAPA::map::qtescape($url);  # Devalidate title cache
            unless ($name) {  $name=(split(/\//,$url))[-1]; }   my $renamed_url=&LONCAPA::map::qtescape($url);
            unless ($name) { $idx++; next; }   &Apache::lonnet::devalidate_title_cache($renamed_url);
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));      } else {
            $idx++;   return 0;
    $shown++;      }
         }      return 1;
  unless ($shown) {  }
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');  
  }  sub editor {
         $r->print("\n</table>\n");      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
  if ($env{'form.markedcopy_url'}) {  
     $r->print(<<ENDPASTE);      my $container= ($env{'form.pagepath'}) ? 'page'
 <p><form name="pasteform" action="/adm/coursedocs" method="post">                             : 'sequence';
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />  
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 ENDPASTE      $folder.'.'.$container);
             $r->print(      return $errtext if ($fatal);
    '<input type="submit" name="pastemarked" value="'.&mt('Paste').  
       '" /> '.&Apache::loncommon::filedescription(      if ($#LONCAPA::map::order<1) {
  (split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.   my $idx=&LONCAPA::map::getresidx();
       $env{'form.markedcopy_title'});   if ($idx<=0) { $idx=1; }
             if ($container eq 'page') {          $LONCAPA::map::order[0]=$idx;
  $r->print(<<PAGEINFO);          $LONCAPA::map::resources[$idx]='';
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />      }
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />     
 PAGEINFO      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
             } else {   &breadcrumbs($folder,$allowed,$type);
  $r->print(<<FOLDERINFO);      $r->print($breadcrumbtrail);
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />     
 FOLDERINFO  # ------------------------------------------------------------ Process commands
     }  
     $r->print('</form></p>');  # ---------------- if they are for this folder and user allowed to make changes
  }      if (($allowed) && ($env{'form.folder'} eq $folder)) {
     }  # set parameters and change order
 }   &snapshotbefore();
   
 sub process_file_upload {   if (&update_parameter()) {
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 # upload a file, if present      return $errtext if ($fatal);
     my $parseaction;   }
    if ($env{'form.parserflag'}) {  
         $parseaction = 'parse';   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
     }  # change order
     my $phase_status;      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
     my $folder=$env{'form.folder'};      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
     if ($folder eq '') {  
         $folder='default';      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     }      return $errtext if ($fatal);
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {   }
         my $errtext='';      
         my $fatal=0;   if ($env{'form.pastemarked'}) {
         my $container='sequence';              my $paste_res =
         if ($env{'form.pagepath'}) {                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
             $container='page';              if ($paste_res eq 'ok') {
         }                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
         ($errtext,$fatal)=                  return $errtext if ($fatal);
               &mapread($coursenum,$coursedom,$folder.'.'.$container);              } elsif ($paste_res ne '') {
         if ($#LONCAPA::map::order<1) {                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
             $LONCAPA::map::order[0]=1;              }
             $LONCAPA::map::resources[1]='';   }
         }  
         if ($fatal) {   $r->print($upload_output);
             return 'failed';  
         }   if (&handle_edit_cmd()) {
         my $destination = 'docs/';      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
         if ($folder =~ /^supplemental/) {      return $errtext if ($fatal);
             $destination = 'supplemental/';   }
         }  # Group import/search
         if (($folder eq 'default') || ($folder eq 'supplemental')) {   if ($env{'form.importdetail'}) {
             $destination .= 'default/';      my @imports;
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
             $destination .=  $2.'/';   if (defined($item)) {
         }      my ($name,$url,$residx)=
 # this is for a course, not a user, so set coursedoc flag   map {&unescape($_)} split(/\=/,$item);
 # probably the only place in the system where this should be "1"      push(@imports, [$name, $url, $residx]);
         my $newidx=&LONCAPA::map::getresidx();   }
         $destination .= $newidx;      }
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
  $parseaction,$allfiles,      $container,'londocs',@imports);
  $codebase);      return $errtext if ($fatal);
         my $ext='false';   }
         if ($url=~/^http\:\/\//) { $ext='true'; }  # Loading a complete map
  $url     = &LONCAPA::map::qtunescape($url);   if ($env{'form.loadmap'}) {
         my $comment=$env{'form.comment'};      if ($env{'form.importmap'}=~/\w/) {
  $comment = &LONCAPA::map::qtunescape($comment);   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
         if ($folder=~/^supplemental/) {      my ($title,$url,$ext,$type)=split(/\:/,$res);
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.      my $idx=&LONCAPA::map::getresidx($url);
                   $env{'user.domain'}.'___&&&___'.$comment;      $LONCAPA::map::resources[$idx]=$res;
         }      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
    }
         $LONCAPA::map::resources[$newidx]=   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     $comment.':'.$url.':'.$ext.':normal:res';      $folder.'.'.$container);
         $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;   return $errtext if ($fatal);
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,      } else {
     $folder.'.'.$container);   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
         if ($fatal) {  
             $$upload_output .= '<p><font color="red">'.$errtext.'</font></p>';      }
             return 'failed';   }
         } else {   &log_differences($plain);
             if ($parseaction eq 'parse') {      }
                 my $total_embedded = keys(%{$allfiles});  # ---------------------------------------------------------------- End commands
                 if ($total_embedded > 0) {  # ---------------------------------------------------------------- Print screen
                     my $num = 0;      my $idx=0;
     my $state = '      my $shown=0;
    <input type="hidden" name="folderpath" value="'.$env{'form.folderpath'}.'" />      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
    <input type="hidden" name="cmd" value="upload_embedded" />   $r->print('<p>'.&mt('Parameters').':<ul>'.
    <input type="hidden" name="newidx" value="'.$newidx.'" />    ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
    <input type="hidden" name="primaryurl" value="'.&escape($url).'" />    ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
     $phase_status = 'phasetwo';    '</ul></p>');
       }                                                                                                    
                     $$upload_output .=       if ($randompick>=0) {
  'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.   $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>');
  &ask_for_embedded_content('/adm/coursedocs',      }
   $state,$allfiles,$codebase);      if ($is_random_order) {
                 } else {   $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>');
                     $$upload_output .= 'No embedded items identified<br />';      }
                 }      $r->print('<table class="LC_docs_editor">');
             }      foreach my $res (@LONCAPA::map::order) {
         }   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     }   $name=&LONCAPA::map::qtescape($name);
     return $phase_status;   $url=&LONCAPA::map::qtescape($url);
 }   unless ($name) {  $name=(split(/\//,$url))[-1]; }
    unless ($name) { $idx++; next; }
 sub ask_for_embedded_content {   $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;       $coursenum));
     my $upload_output = '   $idx++;
    <form name="upload_embedded" action="'.$actionurl.'"   $shown++;
                   method="post" enctype="multipart/form-data">';      }
     $upload_output .= $state;      unless ($shown) {
     $upload_output .= '<b>Upload embedded files</b>:<br />'.   $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
  &Apache::loncommon::start_data_table();      }
       $r->print("\n</table>\n");
     my $num = 0;      if ($allowed) {
     foreach my $embed_file (keys(%{$allfiles})) {          &print_paste_buffer($r,$container);
  $upload_output .= &Apache::loncommon::start_data_table_row().      }
     '<td>'.$embed_file.'</td><td>';      return;
  if ($args->{'ignore_remote_references'}  }
     && $embed_file =~ m{^\w+://}) {  
     $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';  sub process_file_upload {
  } elsif ($args->{'error_on_invalid_names'}      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {  # upload a file, if present
           my $parseaction;
     $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';     if ($env{'form.parserflag'}) {
               $parseaction = 'parse';
  } else {      }
       my $phase_status;
     $upload_output .='      my $folder=$env{'form.folder'};
            <input name="embedded_item_'.$num.'" type="file" value="bob" />      if ($folder eq '') {
            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';          $folder='default';
     my $attrib = join(':',@{$$allfiles{$embed_file}});      }
     $upload_output .=      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  "\n\t\t".          my $errtext='';
  '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.          my $fatal=0;
  $attrib.'" />';          my $container='sequence';
     if (exists($$codebase{$embed_file})) {          if ($env{'form.pagepath'}) {
  $upload_output .=               $container='page';
     "\n\t\t".          }
     '<input name="codebase_'.$num.'" type="hidden" value="'.          ($errtext,$fatal)=
     &escape($$codebase{$embed_file}).'" />';                &mapread($coursenum,$coursedom,$folder.'.'.$container);
     }          if ($#LONCAPA::map::order<1) {
  }              $LONCAPA::map::order[0]=1;
  $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();              $LONCAPA::map::resources[1]='';
  $num++;          }
     }          if ($fatal) {
     $upload_output .= &Apache::loncommon::end_data_table().'<br />              return 'failed';
    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />          }
    <input type ="submit" value="'.&mt('Upload Listed Files').'" />          my $destination = 'docs/';
    '.&mt('(only files for which a location has been provided will be uploaded)').'          if ($folder =~ /^supplemental/) {
    </form>';              $destination = 'supplemental/';
     return $upload_output;          }
 }          if (($folder eq 'default') || ($folder eq 'supplemental')) {
               $destination .= 'default/';
 sub process_secondary_uploads {          } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;              $destination .=  $2.'/';
     my $folder=$env{'form.folder'};          }
     my $destination = 'docs/';  # this is for a course, not a user, so set coursedoc flag
     if ($folder =~ /^supplemental/) {  # probably the only place in the system where this should be "1"
         $destination = 'supplemental/';          my $newidx=&LONCAPA::map::getresidx();
     }          $destination .= $newidx;
     if (($folder eq 'default') || ($folder eq 'supplemental')) {          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
         $destination .= 'default/';   $parseaction,$allfiles,
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {   $codebase);
         $destination .=  $2.'/';          my $ext='false';
     }          if ($url=~m{^http://}) { $ext='true'; }
     $destination .= $newidx;   $url     = &LONCAPA::map::qtunescape($url);
     my ($url,$filename);          my $comment=$env{'form.comment'};
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);   $comment = &LONCAPA::map::qtunescape($comment);
     ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});          if ($folder=~/^supplemental/) {
     return $filename;                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
 }                    $env{'user.domain'}.'___&&&___'.$comment;
           }
 # --------------------------------------------------------------- An entry line  
           $LONCAPA::map::resources[$newidx]=
 sub entryline {      $comment.':'.$url.':'.$ext.':normal:res';
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     $title=&HTML::Entities::encode($title,'"<>&\'');          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
     my $renametitle=$title;      $folder.'.'.$container);
     my $foldertitle=$title;          if ($fatal) {
     my $pagetitle=$title;              $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
     my $orderidx=$LONCAPA::map::order[$index];              return 'failed';
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___($match_username)___&amp;&amp;&amp;___($match_domain)___&amp;&amp;&amp;___(.*)$/ ) {           } else {
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);              if ($parseaction eq 'parse') {
  $renametitle=$4;                  my $total_embedded = keys(%{$allfiles});
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.                  if ($total_embedded > 0) {
     &Apache::loncommon::plainname($2,$3).': <br />'.                      my $num = 0;
     $foldertitle;      my $state = '
     }     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
     $renametitle=~s/\\/\\\\/g;     <input type="hidden" name="cmd" value="upload_embedded" />
     $renametitle=~s/\&quot\;/\\\"/g;     <input type="hidden" name="newidx" value="'.$newidx.'" />
     my $line='<tr>';     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
 # Edit commands     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
     my $container;      $phase_status = 'phasetwo';
     my $folderpath;  
     if ($env{'form.folderpath'}) {                      $$upload_output .=
         $container = 'sequence';   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
  $folderpath=&escape($env{'form.folderpath'});   &Apache::loncommon::ask_for_embedded_content(
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');                              '/adm/coursedocs',$state,$allfiles,$codebase);
     }                  } else {
     my ($pagepath,$pagesymb);                      $$upload_output .= 'No embedded items identified<br />';
     if ($env{'form.pagepath'}) {                  }
         $container = 'page';              }
         $pagepath=&escape($env{'form.pagepath'});          }
         $pagesymb=&escape($env{'form.pagesymb'});      }
     }      return $phase_status;
     my $cpinfo='';  }
     if ($env{'form.markedcopy_url'}) {  
        $cpinfo='&markedcopy_url='.  sub process_secondary_uploads {
                &escape($env{'form.markedcopy_url'}).      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
                '&markedcopy_title='.      my $folder=$env{'form.folder'};
                &escape($env{'form.markedcopy_title'});      my $destination = 'docs/';
     }      if ($folder =~ /^supplemental/) {
     if ($allowed) {          $destination = 'supplemental/';
  my $incindex=$index+1;      }
  my $selectbox='';      if (($folder eq 'default') || ($folder eq 'supplemental')) {
  if (($folder!~/^supplemental/) &&          $destination .= 'default/';
     ($#LONCAPA::map::order>0) &&       } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
     ((split(/\:/,          $destination .=  $2.'/';
      $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]       }
      ne '') &&       $destination .= $newidx;
     ((split(/\:/,      my ($url,$filename);
      $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]       $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
      ne '')) {      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
     $selectbox=      return $filename;
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.  }
  '<select name="newpos" onChange="this.form.submit()">';  
     for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {  sub is_supplemental_title {
  if ($i==$incindex) {      my ($title) = @_;
     $selectbox.='<option value="" selected="1">('.$i.')</option>';      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
  } else {  }
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';  
  }  sub parse_supplemental_title {
     }      my ($title) = @_;
     $selectbox.='</select>';  
  }      my ($foldertitle,$renametitle);
  my %lt=&Apache::lonlocal::texthash(      if ($title =~ /&amp;&amp;&amp;/) {
                 'up' => 'Move Up',   $title = &HTML::Entites::decode($title);
  'dw' => 'Move Down',      }
  'rm' => 'Remove',   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                 'ct' => 'Cut',   $renametitle=$4;
  'rn' => 'Rename',   my ($time,$uname,$udom) = ($1,$2,$3);
  'cp' => 'Copy');   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
  my $nocopy=0;   my $name =  &Apache::loncommon::plainname($uname,$udom);
         my $nocut=0;   $name = &HTML::Entities::encode($name,'"<>&\'');
         if ($url=~/\.(page|sequence)$/) {   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
     foreach (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url))) {      $name.': <br />'.$foldertitle;
  my ($title,$url,$ext,$type)=split(/\:/,$_);      }
  if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {      if (wantarray) {
     $nocopy=1;   return ($title,$foldertitle,$renametitle);
     last;      }
  }      return $title;
     }  }
  }  
         if ($url=~/^\/res\/lib\/templates\//) {   # --------------------------------------------------------------- An entry line
            $nocopy=1;   
            $nocut=1;  sub entryline {
         }      my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
         my $copylink='&nbsp;';  
         my $cutlink='&nbsp;';      my ($foldertitle,$pagetitle,$renametitle);
         if ($env{'form.pagepath'}) {      if (&is_supplemental_title($title)) {
            if (!$nocopy) {   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
                $copylink=(<<ENDCOPY);   $pagetitle = $foldertitle;
 <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>      } else {
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>   $title=&HTML::Entities::encode($title,'"<>&\'');
 ENDCOPY   $renametitle=$title;
            }   $foldertitle=$title;
            if (!$nocut) {   $pagetitle=$title;
                $cutlink=(<<ENDCUT);      }
 <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>  
 <font size="-2" color="#550044">$lt{'ct'}</font></a>      my $orderidx=$LONCAPA::map::order[$index];
 ENDCUT     
             }  
             $line.=(<<END);      $renametitle=~s/\\/\\\\/g;
 <form name="entry_$index" action="/adm/coursedocs" method="post">      $renametitle=~s/\&quot\;/\\\"/g;
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />      $renametitle=~s/ /%20/g;
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />      my $line='<tr>';
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />      my ($form_start,$form_end);
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />  # Edit commands
 <input type="hidden" name="setparms" value="$orderidx" />      my ($container, $type, $esc_path, $path, $symb);
 <input type="hidden" name="changeparms" value="0" />      if ($env{'form.folderpath'}) {
 <td><table border='0' cellspacing='2' cellpadding='0'>   $type = 'folder';
 <tr><td bgcolor="#DDDDDD">          $container = 'sequence';
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>   $esc_path=&escape($env{'form.folderpath'});
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>   $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 <tr><td bgcolor="#DDDDDD">   # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      }
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>      if ($env{'form.pagepath'}) {
 </table></td>          $type = $container = 'page';
 <td>$selectbox          $esc_path=&escape($path = $env{'form.pagepath'});
 </td><td bgcolor="#DDDDDD">   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>          $symb=&escape($env{'form.pagesymb'});
 <font size="-2" color="#990000">$lt{'rm'}</font></a>      }
 $cutlink      my $cpinfo='';
 <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>      if ($allowed) {
 <font size="-2" color="#009900">$lt{'rn'}</font></a>   my $incindex=$index+1;
 $copylink   my $selectbox='';
 END   if (($folder!~/^supplemental/) &&
         } else {      ($#LONCAPA::map::order>0) &&
            if (!$nocopy) {      ((split(/\:/,
                $copylink=(<<ENDCOPY);       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
 <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>       ne '') &&
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>      ((split(/\:/,
 ENDCOPY       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
             }       ne '')) {
             if (!$nocut) {      $selectbox=
                $cutlink=(<<ENDCUT);   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
 <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>   '<select name="newpos" onChange="this.form.submit()">';
 <font size="-2" color="#550044">$lt{'ct'}</font></a>      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
 ENDCUT   if ($i==$incindex) {
             }      $selectbox.='<option value="" selected="1">('.$i.')</option>';
             $line.=(<<END);    } else {
 <form name="entry_$index" action="/adm/coursedocs" method="post">      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   }
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />      }
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      $selectbox.='</select>';
 <input type="hidden" name="setparms" value="$orderidx" />   }
 <input type="hidden" name="changeparms" value="0" />   my %lt=&Apache::lonlocal::texthash(
 <td><table border='0' cellspacing='2' cellpadding='0'>                  'up' => 'Move Up',
 <tr><td bgcolor="#DDDDDD">   'dw' => 'Move Down',
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>   'rm' => 'Remove',
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>                  'ct' => 'Cut',
 <tr><td bgcolor="#DDDDDD">   'rn' => 'Rename',
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>   'cp' => 'Copy');
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>   my $nocopy=0;
 </table></td>          my $nocut=0;
 <td>$selectbox          if ($url=~/\.(page|sequence)$/) {
 </td><td bgcolor="#DDDDDD">      if ($url =~ m{/res/}) {
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>   # no copy for published maps
 <font size="-2" color="#990000">$lt{'rm'}</font></a>   $nocopy = 1;
 $cutlink      } else {
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
 <font size="-2" color="#009900">$lt{'rn'}</font></a>      my ($title,$url,$ext,$type)=split(/\:/,$item);
 $copylink      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
 END   $nocopy=1;
         }   last;
     }      }
 # Figure out what kind of a resource this is   }
     my ($extension)=($url=~/\.(\w+)$/);      }
     my $uploaded=($url=~/^\/*uploaded\//);   }
     my $icon=&Apache::loncommon::icon($url);          if ($url=~/^\/res\/lib\/templates\//) {
     my $isfolder=0;             $nocopy=1;
     my $ispage=0;             $nocut=1;
     my $folderarg;          }
     my $pagearg;          my $copylink='&nbsp;';
     my $pagefile;          my $cutlink='&nbsp;';
     if ($uploaded) {  
  if ($extension eq 'sequence') {   my $skip_confirm = 0;
     $icon=$iconpath.'/folder_closed.gif';   if ( $folder =~ /^supplemental/
     $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;       || ($url =~ m{( /smppg$
     $url='/adm/coursedocs?';      |/syllabus$
     $folderarg=$1;      |/aboutme$
     $isfolder=1;      |/navmaps$
         } elsif ($extension eq 'page') {      |/bulletinboard$
             $icon=$iconpath.'/page.gif';      |\.html$
             $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;      |^/adm/wrapper/ext)}x)) {
             $pagearg=$1;      $skip_confirm = 1;
             $url='/adm/coursedocs?';   }
             $ispage=1;  
  } else {   if (!$nocopy) {
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);      $copylink=(<<ENDCOPY);
  }  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
     }  ENDCOPY
     $url=~s-^http(\&colon\;|:)//-/adm/wrapper/ext/-;          }
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {   if (!$nocut) {
  my $symb=&Apache::lonnet::symbclean(      $cutlink=(<<ENDCUT);
           &Apache::lonnet::declutter('uploaded/'.  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.  ENDCUT
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.          }
            '.sequence').   $form_start = (<<END);
            '___'.$residx.'___'.     <form  action="/adm/coursedocs" method="post">
    &Apache::lonnet::declutter($url));     <input type="hidden" name="${type}path" value="$path" />
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);     <input type="hidden" name="${type}symb" value="$symb" />
  $url=&Apache::lonnet::clutter($url);     <input type="hidden" name="setparms" value="$orderidx" />
  if ($url=~/^\/*uploaded\//) {     <input type="hidden" name="changeparms" value="0" />
     $url=~/\.(\w+)$/;  END
     my $embstyle=&Apache::loncommon::fileembstyle($1);          $form_end = '</form>';
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {   $line.=(<<END);
  $url='/adm/wrapper'.$url;  <td>
     } elsif ($embstyle eq 'ssi') {     <table class="LC_docs_entry_move">
  #do nothing with these        <tr>
     } elsif ($url!~/\.(sequence|page)$/) {           <td>
  $url='/adm/coursedocs/showdoc'.$url;              <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>
     }           </td>
  } elsif ($url=~m|^/ext/|) {         </tr>
     $url='/adm/wrapper'.$url;        <tr>
  }          <td>
         if (&Apache::lonnet::symbverify($symb,$url)) {             <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.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);          </td>
         } else {        </tr>
             $url='';      </table>
         }  </td>
  if ($container eq 'page') {  <td>
     my $symb=$env{'form.pagesymb'};     $form_start
              $selectbox
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);     $form_end
     $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);  </td>
  }  <td class="LC_docs_entry_commands">
     }     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     my $parameterset='&nbsp;';  $cutlink
     if ($isfolder || $extension eq 'sequence') {     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
  my $foldername=&escape($foldertitle);  $copylink
  my $folderpath=$env{'form.folderpath'};  </td>
  if ($folderpath) { $folderpath.='&' };  END
 # Append randompick number, hidden, and encrypted with ":" to foldername,   
 # so it gets transferred between levels      }
  $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,  # Figure out what kind of a resource this is
                                               'parameter_randompick'))[0]      my ($extension)=($url=~/\.(\w+)$/);
                                                .':'.((&LONCAPA::map::getparameter($orderidx,      my $uploaded=($url=~/^\/*uploaded\//);
                                               'parameter_hiddenresource'))[0]=~/^yes$/i)      my $icon=&Apache::loncommon::icon($url);
                                                .':'.((&LONCAPA::map::getparameter($orderidx,      my $isfolder=0;
                                               'parameter_encrypturl'))[0]=~/^yes$/i);      my $ispage=0;
  $url.='folderpath='.&escape($folderpath).$cpinfo;      my $folderarg;
  $parameterset='<label>'.&mt('Randomly Pick: ').      my $pagearg;
     '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randpick_'.$orderidx.'" value="'.      my $pagefile;
     (&LONCAPA::map::getparameter($orderidx,      if ($uploaded) {
                                               'parameter_randompick'))[0].   if ($extension eq 'sequence') {
                                               '" />'.      $icon=$iconpath.'/folder_closed.gif';
 '<font size="-2"><a href="javascript:void(0)">'.&mt('Save').'</a></font></label>';      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
              $url='/adm/coursedocs?';
     }      $folderarg=$1;
     if ($ispage) {      $isfolder=1;
         my $pagename=&escape($pagetitle);          } elsif ($extension eq 'page') {
         my $pagepath;              $icon=$iconpath.'/page.gif';
         my $folderpath=$env{'form.folderpath'};              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
         if ($folderpath) { $pagepath = $folderpath.'&' };              $pagearg=$1;
         $pagepath.=$pagearg.'&'.$pagename;              $url='/adm/coursedocs?';
  my $symb=$env{'form.pagesymb'};              $ispage=1;
  if (!$symb) {   } else {
     my $path='uploaded/'.      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   }
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';      }
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',     
        $residx,      my $orig_url = $url;
        $path.$pagearg.'.page');      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
  }      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
  $url.='pagepath='.&escape($pagepath).   my $symb=&Apache::lonnet::symbclean(
     '&pagesymb='.&escape($symb).$cpinfo;            &Apache::lonnet::declutter('uploaded/'.
     }             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.             $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
  '" border="0"></a></td>'.             '.sequence').
         "<td bgcolor='#FFFFBB'>".($url?"<a href=\"$url\">":'').$title.             '___'.$residx.'___'.
         ($url?'</a>':' <font size="-2">'.&mt('(re-initialize course to access)').'</font>')."</td>";     &Apache::lonnet::declutter($url));
     if (($allowed) && ($folder!~/^supplemental/)) {   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
   my %lt=&Apache::lonlocal::texthash(   $url=&Apache::lonnet::clutter($url);
        'hd' => 'Hidden',   if ($url=~/^\/*uploaded\//) {
        'ec' => 'URL hidden');      $url=~/\.(\w+)$/;
  my $enctext=      my $embstyle=&Apache::loncommon::fileembstyle($1);
     ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
  my $hidtext=   $url='/adm/wrapper'.$url;
     ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');      } elsif ($embstyle eq 'ssi') {
  $line.=(<<ENDPARMS);   #do nothing with these
 <td bgcolor="#BBBBFF"><font size='-2'>      } elsif ($url!~/\.(sequence|page)$/) {
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>   $url='/adm/coursedocs/showdoc'.$url;
 <td bgcolor="#BBBBFF"><font size='-2'>      }
 <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>   } elsif ($url=~m|^/ext/|) {
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>      $url='/adm/wrapper'.$url;
 ENDPARMS      $external = 1;
     }   }
     $line.="</form></tr>";          if (&Apache::lonnet::symbverify($symb,$url)) {
     return $line;      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
 }          } else {
               $url='';
 # ---------------------------------------------------------------- tie the hash          }
    if ($container eq 'page') {
 sub tiehash {      my $symb=$env{'form.pagesymb'};
     my ($mode)=@_;          
     $hashtied=0;      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
     if ($env{'request.course.fn'}) {      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  if ($mode eq 'write') {   }
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",      }
     &GDBM_WRCREAT(),0640)) {      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
                 $hashtied=2;      if ($isfolder || $extension eq 'sequence') {
     }   my $foldername=&escape($foldertitle);
  } else {   my $folderpath=$env{'form.folderpath'};
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",   if ($folderpath) { $folderpath.='&' };
     &GDBM_READER(),0640)) {  # Append randompick number, hidden, and encrypted with ":" to foldername,
                 $hashtied=1;  # so it gets transferred between levels
     }   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
  }                                                'parameter_randompick'))[0]
     }                                                     .':'.((&LONCAPA::map::getparameter($orderidx,
 }                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
                                                  .':'.((&LONCAPA::map::getparameter($orderidx,
 sub untiehash {                                                'parameter_encrypturl'))[0]=~/^yes$/i)
     if ($hashtied) { untie %hash; }                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     $hashtied=0;                                                'parameter_randomorder'))[0]=~/^yes$/i);
     return OK;   $url.='folderpath='.&escape($folderpath).$cpinfo;
 }   $parameterset='<label>'.&mt('Randomly Pick: ').
       '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
 # --------------------------------------------------------------- check on this      (&LONCAPA::map::getparameter($orderidx,
                                                 'parameter_randompick'))[0].
 sub checkonthis {                                                '" />'.
     my ($r,$url,$level,$title)=@_;  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
     $url=&unescape($url);      my $ro_set=
     $alreadyseen{$url}=1;      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
     $r->rflush();   $rand_order_text ='
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {  <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>';  
        $r->print("\n<br />");      }
        for (my $i=0;$i<=$level*5;$i++) {      if ($ispage) {
            $r->print('&nbsp;');          my $pagename=&escape($pagetitle);
        }          my $pagepath;
        $r->print('<a href="'.$url.'" target="cat">'.          my $folderpath=$env{'form.folderpath'};
  ($title?$title:$url).'</a> ');          if ($folderpath) { $pagepath = $folderpath.'&' };
        if ($url=~/^\/res\//) {          $pagepath.=$pagearg.'&'.$pagename;
   my $result=&Apache::lonnet::repcopy(   my $symb=$env{'form.pagesymb'};
                               &Apache::lonnet::filelocation('',$url));   if (!$symb) {
           if ($result eq 'ok') {      my $path='uploaded/'.
              $r->print('<font color="green">'.&mt('ok').'</font>');   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
              $r->rflush();   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
              &Apache::lonnet::countacc($url);      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
              $url=~/\.(\w+)$/;         $residx,
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {         $path.$pagearg.'.page');
  $r->print('<br />');   }
                  $r->rflush();   $url.='pagepath='.&escape($pagepath).
                  for (my $i=0;$i<=$level*5;$i++) {      '&amp;pagesymb='.&escape($symb).$cpinfo;
                      $r->print('&nbsp;');      }
                  }      if ($external) {
                  $r->print('- '.&mt('Rendering').': ');   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
  my ($errorcount,$warningcount)=split(/:/,   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
        &Apache::lonnet::ssi_body($url,      } else {
        ('grade_target'=>'web',   undef($external);
  'return_only_error_and_warning_counts' => 1)));      }
                  if (($errorcount) ||      $line.='
                      ($warningcount)) {    <td class="LC_docs_entry_icon">
      if ($errorcount) {      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.    </td>
   $errorcount.' '.    <td class="LC_docs_entry_title">
   &mt('error(s)').'</b></font> ');      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
                      }    </td>";
      if ($warningcount) {      if (($allowed) && ($folder!~/^supplemental/)) {
                         $r->print('<font color="blue">'.    my %lt=&Apache::lonlocal::texthash(
   $warningcount.' '.         'hd' => 'Hidden',
   &mt('warning(s)').'</font>');         'ec' => 'URL hidden');
                      }   my $enctext=
                  } else {      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
                      $r->print('<font color="green">'.&mt('ok').'</font>');   my $hidtext=
                  }      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
                  $r->rflush();   $line.=(<<ENDPARMS);
              }    <td class="LC_docs_entry_parameter">
      my $dependencies=      $form_start
                 &Apache::lonnet::metadata($url,'dependencies');      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
              foreach (split(/\,/,$dependencies)) {      $form_end
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {    </td>
                     &checkonthis($r,$_,$level+1);    <td class="LC_docs_entry_parameter">
                  }      $form_start
              }      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
           } elsif ($result eq 'unavailable') {      $form_end
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');    </td>
           } elsif ($result eq 'not_found') {    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
       unless ($url=~/\$/) {    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');  ENDPARMS
       } else {      }
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');      $line.="</tr>";
       }      return $line;
           } else {  }
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');  
           }  =pod
       }  
    }  =item tiehash()
 }  
   tie the hash
   
 #  =cut
 # ----------------------------------------------------------------- List Symbs  
 #   sub tiehash {
 sub list_symbs {      my ($mode)=@_;
     my ($r) = @_;      $hashtied=0;
       if ($env{'request.course.fn'}) {
     $r->print(&Apache::loncommon::start_page('Symb List'));   if ($mode eq 'write') {
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     my $navmap = Apache::lonnavmaps::navmap->new();      &GDBM_WRCREAT(),0640)) {
     $r->print("<pre>\n");                  $hashtied=2;
     foreach my $res ($navmap->retrieveResources()) {      }
  $r->print($res->compTitle()."\t".$res->symb()."\n");   } else {
     }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     $r->print("\n</pre>\n");      &GDBM_READER(),0640)) {
     $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');                  $hashtied=1;
 }      }
    }
       }    
 #  }
 # -------------------------------------------------------------- Verify Content  
 #   sub untiehash {
 sub verifycontent {      if ($hashtied) { untie %hash; }
     my ($r) = @_;      $hashtied=0;
     my $type = &Apache::loncommon::course_type();      return OK;
    my $loaderror=&Apache::lonnet::overloaderror($r);  }
    if ($loaderror) { return $loaderror; }  
    $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));  
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));  
    $hashtied=0;  
    undef %alreadyseen;  sub checkonthis {
    %alreadyseen=();      my ($r,$url,$level,$title)=@_;
    &tiehash();      $url=&unescape($url);
    foreach (keys %hash) {      $alreadyseen{$url}=1;
        if ($hash{$_}=~/\.(page|sequence)$/) {      $r->rflush();
    if (($_=~/^src_/) && ($alreadyseen{&unescape($hash{$_})})) {      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
        $r->print('<hr /><font color="red">'.         $r->print("\n<br />");
  &mt('The following sequence or page is included more than once in your '.$type.': ').         if ($level==0) {
  &unescape($hash{$_}).'</font><br />'.             $r->print("<br />");
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));         }
    }         for (my $i=0;$i<=$level*5;$i++) {
        }             $r->print('&nbsp;');
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$_})})) {         }
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});         $r->print('<a href="'.$url.'" target="cat">'.
        }   ($title?$title:$url).'</a> ');
    }         if ($url=~/^\/res\//) {
    &untiehash();    my $result=&Apache::lonnet::repcopy(
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.                                &Apache::lonnet::filelocation('',$url));
      &mt('Return to DOCS').'</a>');            if ($result eq 'ok') {
 }               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
                $r->rflush();
                &Apache::lonnet::countacc($url);
 # -------------------------------------------------------------- Check Versions               $url=~/\.(\w+)$/;
                if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
 sub devalidateversioncache {   $r->print('<br />');
     my $src=shift;                   $r->rflush();
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.                   for (my $i=0;$i<=$level*5;$i++) {
   &Apache::lonnet::clutter($src));                       $r->print('&nbsp;');
 }                   }
                    $r->print('- '.&mt('Rendering:').' ');
 sub checkversions {   my ($errorcount,$warningcount)=split(/:/,
     my ($r) = @_;         &Apache::lonnet::ssi_body($url,
     my $type = &Apache::loncommon::course_type();         ('grade_target'=>'web',
     $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));   'return_only_error_and_warning_counts' => 1)));
     $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));                   if (($errorcount) ||
     my $header='';                       ($warningcount)) {
     my $startsel='';       if ($errorcount) {
     my $monthsel='';                          $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
     my $weeksel='';                            &mt('[quant,_1,error]',$errorcount).'</span>');
     my $daysel='';                       }
     my $allsel='';       if ($warningcount) {
     my %changes=();                          $r->print('<span class="LC_warning">'.
     my $starttime=0;                            &mt('[quant,_1,warning]',$warningcount).'</span>');
     my $haschanged=0;                       }
     my %setversions=&Apache::lonnet::dump('resourceversions',                   } else {
   $env{'course.'.$env{'request.course.id'}.'.domain'},                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
   $env{'course.'.$env{'request.course.id'}.'.num'});                   }
                    $r->rflush();
     $hashtied=0;               }
     &tiehash();       my $dependencies=
     my %newsetversions=();                  &Apache::lonnet::metadata($url,'dependencies');
     if ($env{'form.setmostrecent'}) {               foreach my $dep (split(/\,/,$dependencies)) {
  $haschanged=1;   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
  foreach (keys %hash) {                      &checkonthis($r,$dep,$level+1);
     if ($_=~/^ids\_(\/res\/.+)$/) {                   }
  $newsetversions{$1}='mostrecent';               }
                 &devalidateversioncache($1);            } elsif ($result eq 'unavailable') {
     }               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
  }            } elsif ($result eq 'not_found') {
     } elsif ($env{'form.setcurrent'}) {        unless ($url=~/\$/) {
  $haschanged=1;    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
  foreach (keys %hash) {        } else {
     if ($_=~/^ids\_(\/res\/.+)$/) {    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
  my $getvers=&Apache::lonnet::getversion($1);        }
  if ($getvers>0) {            } else {
     $newsetversions{$1}=$getvers;               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     &devalidateversioncache($1);            }
  }         }
     }      }
  }  }
     } elsif ($env{'form.setversions'}) {  
  $haschanged=1;  
  foreach (keys %env) {  
     if ($_=~/^form\.set_version_(.+)$/) {  =pod
  my $src=$1;  
  if (($env{$_}) && ($env{$_} ne $setversions{$src})) {  =item list_symbs()
     $newsetversions{$src}=$env{$_};  
     &devalidateversioncache($src);  List Symbs
  }  
     }  =cut
  }  
     }  sub list_symbs {
     if ($haschanged) {      my ($r) = @_;
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,  
   $env{'course.'.$env{'request.course.id'}.'.domain'},      my $type = &Apache::loncommon::course_type();
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {      $r->print(&Apache::loncommon::start_page('Symb List'));
     $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
  } else {      my $navmap = Apache::lonnavmaps::navmap->new();
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</font></h1>');      if (!defined($navmap)) {
  }          $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
  &mark_hash_old();                    '<div class="LC_error">'.
     }                    &mt('Unable to retrieve information about course contents').
     &changewarning($r,'');                    '</div>');
     if ($env{'form.timerange'} eq 'all') {          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
 # show all documents      } else {
  $header=&mt('All Documents in '.$type);          $r->print("<pre>\n");
  $allsel=1;          foreach my $res ($navmap->retrieveResources()) {
  foreach (keys %hash) {      $r->print($res->compTitle()."\t".$res->symb()."\n");
     if ($_=~/^ids\_(\/res\/.+)$/) {          }
  my $src=$1;          $r->print("\n</pre>\n");
  $changes{$src}=1;      }
     }      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
  }  }
     } else {  
 # show documents which changed  
  %changes=&Apache::lonnet::dump  sub verifycontent {
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},      my ($r) = @_;
                      $env{'course.'.$env{'request.course.id'}.'.num'});      my $type = &Apache::loncommon::course_type();
  my $firstkey=(keys %changes)[0];     my $loaderror=&Apache::lonnet::overloaderror($r);
  unless ($firstkey=~/^error\:/) {     if ($loaderror) { return $loaderror; }
     unless ($env{'form.timerange'}) {     $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
  $env{'form.timerange'}=604800;     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
     }     $hashtied=0;
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '     undef %alreadyseen;
  .&mt('seconds');     %alreadyseen=();
     if ($env{'form.timerange'}==-1) {     &tiehash();
  $seltext='since start of course';     foreach my $key (keys(%hash)) {
  $startsel='selected';         if ($hash{$key}=~/\.(page|sequence)$/) {
  $env{'form.timerange'}=time;     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
     }         $r->print('<hr /><span class="LC_error">'.
     $starttime=time-$env{'form.timerange'};   &mt('The following sequence or page is included more than once in your '.$type.': ').
     if ($env{'form.timerange'}==2592000) {   &unescape($hash{$key}).'</span><br />'.
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
  $monthsel='selected';     }
     } elsif ($env{'form.timerange'}==604800) {         }
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
  $weeksel='selected';             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
     } elsif ($env{'form.timerange'}==86400) {         }
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';     }
  $daysel='selected';     &untiehash();
     }     $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.
     $header=&mt('Content changed').' '.$seltext;       &mt('Return to DOCS').'</a>');
  } else {  }
     $header=&mt('No content modifications yet.');  
  }  
     }  sub devalidateversioncache {
     %setversions=&Apache::lonnet::dump('resourceversions',      my $src=shift;
   $env{'course.'.$env{'request.course.id'}.'.domain'},      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
   $env{'course.'.$env{'request.course.id'}.'.num'});    &Apache::lonnet::clutter($src));
     my %lt=&Apache::lonlocal::texthash  }
       ('st' => 'Version changes since start of '.$type,  
        'lm' => 'Version changes since last Month',  sub checkversions {
        'lw' => 'Version changes since last Week',      my ($r) = @_;
        'sy' => 'Version changes since Yesterday',      my $type = &Apache::loncommon::course_type();
                'al' => 'All Resources (possibly large output)',      $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
        'sd' => 'Display',      $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
        'fi' => 'File',      my $header='';
        'md' => 'Modification Date',      my $startsel='';
                'mr' => 'Most recently published Version',      my $monthsel='';
        've' => 'Version used in '.$type,      my $weeksel='';
                'vu' => 'Set Version to be used in '.$type,      my $daysel='';
 'sv' => 'Set Versions to be used in '.$type.' according to Selections below',      my $allsel='';
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',      my %changes=();
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      my $starttime=0;
        'di' => 'Differences');      my $haschanged=0;
     $r->print(<<ENDHEADERS);      my %setversions=&Apache::lonnet::dump('resourceversions',
 <form action="/adm/coursedocs" method="post">    $env{'course.'.$env{'request.course.id'}.'.domain'},
 <input type="hidden" name="versions" value="1" />    $env{'course.'.$env{'request.course.id'}.'.num'});
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />  
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />      $hashtied=0;
 <select name="timerange">      &tiehash();
 <option value='all' $allsel>$lt{'al'}</option>      my %newsetversions=();
 <option value="-1" $startsel>$lt{'st'}</option>      if ($env{'form.setmostrecent'}) {
 <option value="2592000" $monthsel>$lt{'lm'}</option>   $haschanged=1;
 <option value="604800" $weeksel>$lt{'lw'}</option>   foreach my $key (keys(%hash)) {
 <option value="86400" $daysel>$lt{'sy'}</option>      if ($key=~/^ids\_(\/res\/.+)$/) {
 </select>   $newsetversions{$1}='mostrecent';
 <input type="submit" name="display" value="$lt{'sd'}" />                  &devalidateversioncache($1);
 <h3>$header</h3>      }
 <input type="submit" name="setversions" value="$lt{'sv'}" />   }
 <table border="0">      } elsif ($env{'form.setcurrent'}) {
 ENDHEADERS   $haschanged=1;
     foreach (sort keys %changes) {   foreach my $key (keys(%hash)) {
  if ($changes{$_}>$starttime) {      if ($key=~/^ids\_(\/res\/.+)$/) {
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);   my $getvers=&Apache::lonnet::getversion($1);
     my $currentversion=&Apache::lonnet::getversion($_);   if ($getvers>0) {
     if ($currentversion<0) {      $newsetversions{$1}=$getvers;
  $currentversion=&mt('Could not be determined.');      &devalidateversioncache($1);
     }   }
     my $linkurl=&Apache::lonnet::clutter($_);      }
     $r->print(   }
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.      } elsif ($env{'form.setversions'}) {
       &Apache::lonnet::gettitle($linkurl).   $haschanged=1;
                       '</b></font></td></tr>'.   foreach my $key (keys(%env)) {
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      if ($key=~/^form\.set_version_(.+)$/) {
                       '<td colspan="4">'.   my $src=$1;
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
       '</a></td></tr>'.      $newsetversions{$src}=$env{$key};
                       '<tr><td></td>'.      &devalidateversioncache($src);
                       '<td title="'.$lt{'md'}.'">'.   }
       &Apache::lonlocal::locallocaltime(      }
                            &Apache::lonnet::metadata($root.'.'.$extension,   }
                                                      'lastrevisiondate')      }
                                                         ).      if ($haschanged) {
                       '</td>'.          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.    $env{'course.'.$env{'request.course.id'}.'.domain'},
                       '<font size="+1">'.$currentversion.'</font>'.    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
                       '</nobr></td>'.      $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
                       '<td title="'.$lt{'ve'}.'"><nobr>In '.$type.': '.   } else {
                       '<font size="+1">');      $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
 # Used in course   }
     my $usedversion=$hash{'version_'.$linkurl};   &mark_hash_old();
     if (($usedversion) && ($usedversion ne 'mostrecent')) {      }
  $r->print($usedversion);      &changewarning($r,'');
     } else {      if ($env{'form.timerange'} eq 'all') {
  $r->print($currentversion);  # show all documents
     }   $header=&mt('All Documents in '.$type);
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.   $allsel=1;
                       '<nobr>Use: ');   foreach my $key (keys(%hash)) {
 # Set version      if ($key=~/^ids\_(\/res\/.+)$/) {
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},   my $src=$1;
       'set_version_'.$linkurl,   $changes{$src}=1;
       ('select_form_order' =>      }
        ['',1..$currentversion,'mostrecent'],   }
        '' => '',      } else {
        'mostrecent' => 'most recent',  # show documents which changed
        map {$_,$_} (1..$currentversion))));   %changes=&Apache::lonnet::dump
     $r->print('</nobr></td></tr><tr><td></td>');   ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},
     my $lastold=1;                       $env{'course.'.$env{'request.course.id'}.'.num'});
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {   my $firstkey=(keys(%changes))[0];
  my $url=$root.'.'.$prevvers.'.'.$extension;   unless ($firstkey=~/^error\:/) {
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<      unless ($env{'form.timerange'}) {
     $starttime) {   $env{'form.timerange'}=604800;
     $lastold=$prevvers;      }
  }      my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
     }   .&mt('seconds');
             #       if ($env{'form.timerange'}==-1) {
             # Code to figure out how many version entries should go in   $seltext='since start of course';
             # each of the four columns   $startsel='selected';
             my $entries_per_col = 0;   $env{'form.timerange'}=time;
             my $num_entries = ($currentversion-$lastold);      }
             if ($num_entries % 4 == 0) {      $starttime=time-$env{'form.timerange'};
                 $entries_per_col = $num_entries/4;      if ($env{'form.timerange'}==2592000) {
             } else {   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
                 $entries_per_col = $num_entries/4 + 1;   $monthsel='selected';
             }      } elsif ($env{'form.timerange'}==604800) {
             my $entries_count = 0;   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
             $r->print('<td valign="top"><font size="-2">');    $weeksel='selected';
             my $cols_output = 1;      } elsif ($env{'form.timerange'}==86400) {
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
  my $url=$root.'.'.$prevvers.'.'.$extension;   $daysel='selected';
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).      }
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      $header=&mt('Content changed').' '.$seltext;
   &Apache::lonlocal::locallocaltime(   } else {
                                 &Apache::lonnet::metadata($url,      $header=&mt('No content modifications yet.');
                                                           'lastrevisiondate')   }
                                                             ).      }
   ')');      %setversions=&Apache::lonnet::dump('resourceversions',
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {    $env{'course.'.$env{'request.course.id'}.'.domain'},
                     $r->print(' <a href="/adm/diff?filename='.    $env{'course.'.$env{'request.course.id'}.'.num'});
       &Apache::lonnet::clutter($root.'.'.$extension).      my %lt=&Apache::lonlocal::texthash
       '&versionone='.$prevvers.        ('st' => 'Version changes since start of '.$type,
       '">'.&mt('Diffs').'</a>');         'lm' => 'Version changes since last Month',
  }         'lw' => 'Version changes since last Week',
  $r->print('</nobr><br />');         'sy' => 'Version changes since Yesterday',
                 if (++$entries_count % $entries_per_col == 0) {                 'al' => 'All Resources (possibly large output)',
                     $r->print('</font></td>');         'sd' => 'Display',
                     if ($cols_output != 4) {         'fi' => 'File',
                         $r->print('<td valign="top"><font size="-2">');         'md' => 'Modification Date',
                         $cols_output++;                 'mr' => 'Most recently published Version',
                     }         've' => 'Version used in '.$type,
                 }                 'vu' => 'Set Version to be used in '.$type,
     }  'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
             while($cols_output++ < 4) {  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
                 $r->print('</font></td><td><font>')  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
             }         'di' => 'Differences');
     $r->print('</font></td></tr>'."\n");      $r->print(<<ENDHEADERS);
  }  <form action="/adm/coursedocs" method="post">
     }  <input type="hidden" name="versions" value="1" />
     $r->print('</table></form>');  <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
     $r->print('<h1>'.&mt('Done').'.</h1>');  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
   <select name="timerange">
     &untiehash();  <option value='all' $allsel>$lt{'al'}</option>
 }  <option value="-1" $startsel>$lt{'st'}</option>
   <option value="2592000" $monthsel>$lt{'lm'}</option>
 sub mark_hash_old {  <option value="604800" $weeksel>$lt{'lw'}</option>
     my $retie_hash=0;  <option value="86400" $daysel>$lt{'sy'}</option>
     if ($hashtied) {  </select>
  $retie_hash=1;  <input type="submit" name="display" value="$lt{'sd'}" />
  &untiehash();  <h3>$header</h3>
     }  <input type="submit" name="setversions" value="$lt{'sv'}" />
     &tiehash('write');  <table border="0">
     $hash{'old'}=1;  ENDHEADERS
     &untiehash();      foreach my $key (sort(keys(%changes))) {
     if ($retie_hash) { &tiehash(); }   if ($changes{$key}>$starttime) {
 }      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
       my $currentversion=&Apache::lonnet::getversion($key);
 sub is_hash_old {      if ($currentversion<0) {
     my $untie_hash=0;   $currentversion=&mt('Could not be determined.');
     if (!$hashtied) {      }
  $untie_hash=1;      my $linkurl=&Apache::lonnet::clutter($key);
  &tiehash();      $r->print(
     }        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
     my $return=$hash{'old'};        &Apache::lonnet::gettitle($linkurl).
     if ($untie_hash) { &untiehash(); }                        '</b></font></td></tr>'.
     return $return;                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 }                        '<td colspan="4">'.
                         '<a href="'.$linkurl.'" target="cat">'.$linkurl.
 sub changewarning {        '</a></td></tr>'.
     my ($r,$postexec,$message,$url)=@_;                        '<tr><td></td>'.
     if (!&is_hash_old()) { return; }                        '<td title="'.$lt{'md'}.'">'.
     my $pathvar='folderpath';        &Apache::lonlocal::locallocaltime(
     my $path=&escape($env{'form.folderpath'});                             &Apache::lonnet::metadata($root.'.'.$extension,
     if (!defined($url)) {                                                       'lastrevisiondate')
  if (defined($env{'form.pagepath'})) {                                                          ).
     $pathvar='pagepath';                        '</td>'.
     $path=&escape($env{'form.pagepath'});                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
     $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});                        '<font size="+1">'.$currentversion.'</font>'.
  }                        '</span></td>'.
  $url='/adm/coursedocs?'.$pathvar.'='.$path;                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
     }                        '<font size="+1">');
     my $course_type = &Apache::loncommon::course_type();  # Used in course
     if (!defined($message)) {      my $usedversion=$hash{'version_'.$linkurl};
  $message='Changes will become active for your current session after [_1], or the next time you log in.';      if (($usedversion) && ($usedversion ne 'mostrecent')) {
     }   $r->print($usedversion);
     $r->print("\n\n".      } else {
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".    $r->print($currentversion);
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.      }
 '<input type="hidden" name="orgurl" value="'.$url.      $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.                        '<span class="LC_nobreak">Use: ');
 &mt($message,' <input type="hidden" name="'.  # Set version
     $env{'request.role'}.'" value="1" /><input type="button" value="'.      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
     &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').        'set_version_'.$linkurl,
 $help{'Caching'}.'</font></h3></form>'."\n\n");        ('select_form_order' =>
 }         ['',1..$currentversion,'mostrecent'],
          '' => '',
 # =========================================== Breadcrumbs for special functions         'mostrecent' => 'most recent',
          map {$_,$_} (1..$currentversion))));
 sub init_breadcrumbs {      $r->print('</span></td></tr><tr><td></td>');
     my ($form,$text)=@_;      my $lastold=1;
     &Apache::lonhtmlcommon::clear_breadcrumbs();      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",   my $url=$root.'.'.$prevvers.'.'.$extension;
     text=>&Apache::loncommon::course_type()." Documents",   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
     faq=>273,      $starttime) {
     bug=>'Instructor Interface',      $lastold=$prevvers;
                                             help => 'Docs_Adding_Course_Doc'});   }
     &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',      }
     text=>$text,              #
     faq=>273,              # Code to figure out how many version entries should go in
     bug=>'Instructor Interface'});              # each of the four columns
 }              my $entries_per_col = 0;
               my $num_entries = ($currentversion-$lastold);
 # ================================================================ Main Handler              if ($num_entries % 4 == 0) {
 sub handler {                  $entries_per_col = $num_entries/4;
     my $r = shift;              } else {
     &Apache::loncommon::content_type($r,'text/html');                  $entries_per_col = $num_entries/4 + 1;
     $r->send_http_header;              }
     return OK if $r->header_only;              my $entries_count = 0;
     my $type = &Apache::loncommon::course_type();              $r->print('<td valign="top"><font size="-2">');
               my $cols_output = 1;
 # --------------------------------------------- Initialize help topics for this              for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
     foreach ('Adding_Course_Doc','Main_Course_Documents',   my $url=$root.'.'.$prevvers.'.'.$extension;
      'Adding_External_Resource','Navigate_Content',   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
      'Adding_Folders','Docs_Overview', 'Load_Map',    '">'.&mt('Version').' '.$prevvers.'</a> ('.
      'Supplemental','Score_Upload_Form','Adding_Pages',    &Apache::lonlocal::locallocaltime(
      'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',                                  &Apache::lonnet::metadata($url,
      'Check_Resource_Versions','Verify_Content') {                                                            'lastrevisiondate')
  $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);                                                              ).
     }    ')');
     # Composite help files   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(                      $r->print(' <a href="/adm/diff?filename='.
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');        &Apache::lonnet::clutter($root.'.'.$extension).
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(        '&versionone='.$prevvers.
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');        '">'.&mt('Diffs').'</a>');
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(   }
     'Option_Response_Simple');   $r->print('</span><br />');
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(                  if (++$entries_count % $entries_per_col == 0) {
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');                      $r->print('</font></td>');
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(                      if ($cols_output != 4) {
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');                          $r->print('<td valign="top"><font size="-2">');
     $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');                          $cols_output++;
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');                      }
                   }
 # does this user have privileges to modify docs      }
     my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});              while($cols_output++ < 4) {
   if ($allowed && $env{'form.verify'}) {                  $r->print('</font></td><td><font>')
       &init_breadcrumbs('verify','Verify Content');              }
       &verifycontent($r);      $r->print('</font></td></tr>'."\n");
   } elsif ($allowed && $env{'form.listsymbs'}) {   }
       &init_breadcrumbs('listsymbs','List Symbs');      }
       &list_symbs($r);      $r->print('</table></form>');
   } elsif ($allowed && $env{'form.docslog'}) {      $r->print('<h1>'.&mt('Done').'.</h1>');
       &init_breadcrumbs('docslog','Show Log');  
       &docs_change_log($r);      &untiehash();
   } elsif ($allowed && $env{'form.versions'}) {  }
       &init_breadcrumbs('versions','Check/Set Resource Versions');  
       &checkversions($r);  sub mark_hash_old {
   } elsif ($allowed && $env{'form.dumpcourse'}) {      my $retie_hash=0;
       &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');      if ($hashtied) {
       &dumpcourse($r);   $retie_hash=1;
   } elsif ($allowed && $env{'form.exportcourse'}) {   &untiehash();
       &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');      }
       &exportcourse($r);      &tiehash('write');
   } else {      $hash{'old'}=1;
 # is this a standard course?      &untiehash();
       if ($retie_hash) { &tiehash(); }
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);  }
     my $forcestandard = 0;  
     my $forcesupplement;  sub is_hash_old {
     my $script='';      my $untie_hash=0;
     my $showdoc=0;      if (!$hashtied) {
     my $containertag;   $untie_hash=1;
     my $uploadtag;   &tiehash();
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},      }
     ['folderpath','pagepath',      my $return=$hash{'old'};
      'pagesymb','markedcopy_url',      if ($untie_hash) { &untiehash(); }
      'markedcopy_title']);      return $return;
     if ($env{'form.folderpath'}) {  }
  my (@folderpath)=split('&',$env{'form.folderpath'});  
  $env{'form.foldername'}=&unescape(pop(@folderpath));  sub changewarning {
  $env{'form.folder'}=pop(@folderpath);      my ($r,$postexec,$message,$url)=@_;
     }      if (!&is_hash_old()) { return; }
     if ($env{'form.pagepath'}) {      my $pathvar='folderpath';
         my (@pagepath)=split('&',$env{'form.pagepath'});      my $path=&escape($env{'form.folderpath'});
         $env{'form.pagename'}=&unescape(pop(@pagepath));      if (!defined($url)) {
         $env{'form.folder'}=pop(@pagepath);   if (defined($env{'form.pagepath'})) {
         $containertag = '<input type="hidden" name="pagepath" value="" />'.      $pathvar='pagepath';
     '<input type="hidden" name="pagesymb" value="" />';      $path=&escape($env{'form.pagepath'});
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
     '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';   }
     }   $url='/adm/coursedocs?'.$pathvar.'='.$path;
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {      }
        $showdoc='/'.$1;      my $course_type = &Apache::loncommon::course_type();
     }      if (!defined($message)) {
     unless ($showdoc) { # got called from remote   $message='Changes will become active for your current session after [_1], or the next time you log in.';
        if (($env{'form.folder'}=~/^(?:group|default)_/) ||       }
           ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {      $r->print("\n\n".
            $forcestandard = 1;  '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
        }   '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
        $forcesupplement=($env{'form.folder'}=~/^supplemental_/);  '<input type="hidden" name="orgurl" value="'.$url.
   '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
        if ($allowed) {   &mt($message,' <input type="hidden" name="'.
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);      $env{'request.role'}.'" value="1" /><input type="button" value="'.
          $script=&Apache::lonratedt::editscript('simple');       &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
        }  $help{'Caching'}.'</span></h3></form>'."\n\n");
     } else { # got called in sequence from course  }
        $allowed=0;  
     }  
   sub init_breadcrumbs {
 # get course data      my ($form,$text)=@_;
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};      &Apache::lonhtmlcommon::clear_breadcrumbs();
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
       text=>"Edit ".&Apache::loncommon::course_type(),
 # get personal data       faq=>273,
     my $uname=$env{'user.name'};      bug=>'Instructor Interface',
     my $udom=$env{'user.domain'};                                              help => 'Docs_Adding_Course_Doc'});
     my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
       text=>$text,
 # graphics settings      faq=>273,
       bug=>'Instructor Interface'});
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");  }
   
     if ($allowed) {  
  $script .= &editing_js($udom,$uname);  
     }  
 # -------------------------------------------------------------------- Body tag  sub handler {
     $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';      my $r = shift;
     $r->print(&Apache::loncommon::start_page("$type Documents", $script,      &Apache::loncommon::content_type($r,'text/html');
      {'force_register' => $showdoc,}).      $r->send_http_header;
       &Apache::loncommon::help_open_menu('','',273,'RAT'));      return OK if $r->header_only;
         my $type = &Apache::loncommon::course_type();
   my %allfiles = ();  
   my %codebase = ();  
   my ($upload_result,$upload_output);  # --------------------------------------------- Initialize help topics for this
   if ($allowed) {      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
       if (($env{'form.uploaddoc.filename'}) &&                 'Adding_External_Resource','Navigate_Content',
   ($env{'form.cmd'}=~/^upload_(\w+)/)) {                 'Adding_Folders','Docs_Overview', 'Load_Map',
 # Process file upload - phase one - upload and parse primary file.                   'Supplemental','Score_Upload_Form','Adding_Pages',
           $upload_result = &process_file_upload(\$upload_output,$coursenum,                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
  $coursedom,\%allfiles,                 'Check_Resource_Versions','Verify_Content') {
  \%codebase,$1);   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
           if ($upload_result eq 'phasetwo') {      }
               $r->print($upload_output);      # Composite help files
           }      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
       } elsif ($env{'form.phasetwo'}) {      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
           my %newname = ();      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
           my %origname = ();      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
           my %attribs = ();      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
           my $updateflag = 0;      'Option_Response_Simple');
           my $residx = $env{'form.newidx'};      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
           my $primary_url = &unescape($env{'form.primaryurl'});      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 # Process file upload - phase two - gather secondary files.      $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
               if ($env{'form.embedded_item_'.$i.'.filename'}) {      $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
                   my $javacodebase;      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);  
                   $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});  # does this user have privileges to modify docs
                   if (exists($env{'form.embedded_codebase_'.$i})) {      my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                       $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});      if ($allowed && $env{'form.verify'}) {
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;         &init_breadcrumbs('verify','Verify Content');
                   }        &verifycontent($r);
                   my @attributes = ();    } elsif ($allowed && $env{'form.listsymbs'}) {
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {        &init_breadcrumbs('listsymbs','List Symbs');
                       @attributes = split/:/,$env{'form.embedded_attrib_'.$i};        &list_symbs($r);
                   } else {    } elsif ($allowed && $env{'form.docslog'}) {
                       @attributes = ($env{'form.embedded_attrib_'.$i});        &init_breadcrumbs('docslog','Show Log');
                   }        &docs_change_log($r);
                   foreach (@attributes) {    } elsif ($allowed && $env{'form.versions'}) {
                       push(@{$attribs{$i}},&unescape($_));        &init_breadcrumbs('versions','Check/Set Resource Versions');
                   }        &checkversions($r);
                   if ($javacodebase) {    } elsif ($allowed && $env{'form.dumpcourse'}) {
                       $codebase{$i} = $javacodebase;        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
                       $codebase{$i} =~ s#/$##;        &dumpcourse($r);
                       $updateflag = 1;    } elsif ($allowed && $env{'form.exportcourse'}) {
                   }        &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
               }        &exportcourse($r);
               unless ($newname{$i} eq $origname{$i}) {    } else {
                   $updateflag = 1;  # is this a standard course?
               }  
           }      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 # Process file upload - phase three - modify primary file      my $forcestandard = 0;
           if ($updateflag) {      my $forcesupplement;
               my ($content,$rtncode);      my $script='';
               my $updateflag = 0;      my $showdoc=0;
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);      my $containertag;
               if ($getstatus eq 'ok') {      my $uploadtag;
                   foreach my $item (keys %newname) {  
                       if ($newname{$item} ne $origname{$item}) {  
                           my $attrib_regexp = '';      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                           if (@{$attribs{$item}} > 1) {      ['folderpath','pagepath',
                               $attrib_regexp = join('|',@{$attribs{$item}});       'pagesymb']);
                           } else {  # No folderpath, no pagepath, see if we have something stored
                               $attrib_regexp = $attribs{$item}[0];      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
                           }          &Apache::loncommon::restore_course_settings('docs_folderpath',
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {                                                {'folderpath' => 'scalar'});
                           }       }
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;       if (!$env{'form.folderpath'}) {
                       }          &Apache::loncommon::restore_course_settings('docs_folderpath',
                       if (exists($codebase{$item})) {                                                {'pagepath' => 'scalar'});
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs      }
                       }      if ($env{'form.pagepath'}) {
                   }         $env{'form.folderpath'}='';
 # Save edited file.      }
                   my $saveresult;      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};          $env{'form.folderpath'} = 'supplemental&'.
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};                                    &escape(&mt('Supplemental '.$type.' Documents')).'&'.
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);                                    $env{'form.folderpath'};
               } else {      }
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);       &Apache::loncommon::store_course_settings('docs_folderpath',
               }                                                  {'pagepath' => 'scalar',
           }                                                   'folderpath' => 'scalar'});
       }      if ($env{'form.folderpath'}) {
   }   my (@folderpath)=split('&',$env{'form.folderpath'});
    $env{'form.foldername'}=&unescape(pop(@folderpath));
   unless ($showdoc ||  $upload_result eq 'phasetwo') {   $env{'form.folder'}=pop(@folderpath);
 # -----------------------------------------------------------------------------      }
        my %lt=&Apache::lonlocal::texthash(      if ($env{'form.pagepath'}) {
                 'uplm' => 'Upload a new main '.lc($type).' document',          my (@pagepath)=split('&',$env{'form.pagepath'});
                 'upls' => 'Upload a new supplemental '.lc($type).' document',          $env{'form.pagename'}=&unescape(pop(@pagepath));
                 'impp' => 'Import a document',          $env{'form.folder'}=pop(@pagepath);
                 'pubd' => 'Published documents',          $containertag = '<input type="hidden" name="pagepath" value="" />'.
  'copm' => 'All documents out of a published map into this folder',      '<input type="hidden" name="pagesymb" value="" />';
                 'spec' => 'Special documents',          $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
                 'upld' => 'Upload Document',      '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
                 'srch' => 'Search',      }
                 'impo' => 'Import',      if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
  'book' => 'Import Bookmarks',         $showdoc='/'.$1;
                 'selm' => 'Select Map',      }
                 'load' => 'Load Map',      unless ($showdoc) { # got called from remote
                 'reco' => 'Recover Deleted Resources',         if (($env{'form.folder'}=~/^(?:group|default)_/) ||
                 'newf' => 'New Folder',            ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
                 'newp' => 'New Composite Page',             $forcestandard = 1;
                 'extr' => 'External Resource',         }
                 'syll' => 'Syllabus',         $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
                 'navc' => 'Navigate Contents',  
                 'sipa' => 'Simple Page',         if ($allowed) {
                 'sipr' => 'Simple Problem',           &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
                 'drbx' => 'Drop Box',           $script=&Apache::lonratedt::editscript('simple');
                 'scuf' => 'Score Upload Form',         }
                 'bull' => 'Bulletin Board',      } else { # got called in sequence from course
                 'mypi' => 'My Personal Info',         $allowed=0;
                 'grpo' => 'Group Files',      }
  'abou' => 'About User',  
                 'imsf' => 'Import IMS package',  # get course data
                 'file' =>  'File',      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
                 'title' => 'Title',      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                 'comment' => 'Comment',  
                 'parse' => 'If HTML file, upload embedded images/multimedia files'  # get personal data
   );      my $uname=$env{'user.name'};
 # -----------------------------------------------------------------------------      my $udom=$env{'user.domain'};
     if ($allowed) {      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
        my $dumpbut=&dumpbutton();  
        my $exportbut=&exportbutton();  # graphics settings
        my %lt=&Apache::lonlocal::texthash(  
  'vc' => 'Verify Content',      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
  'cv' => 'Check/Set Resource Versions',  
  'ls' => 'List Symbs',      if ($allowed) {
                                          'sl' => 'Show Log'   $script .= &editing_js($udom,$uname);
   );      }
   # -------------------------------------------------------------------- Body tag
        my $folderpath=$env{'form.folderpath'};      $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
        if (!$folderpath) {      my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
    if ($env{'form.folder'} eq '' ||      $r->print(&Apache::loncommon::start_page("$type Documents", $script,
        $env{'form.folder'} eq 'supplemental') {      {'force_register' => $showdoc,
        $folderpath='default&'.                                       'bread_crumbs' => $brcrum}).
    &escape(&mt('Main '.$type.' Documents'));        &Apache::loncommon::help_open_menu('','',273,'RAT'));
    }   
        }    my %allfiles = ();
        unless ($env{'form.pagepath'}) {    my %codebase = ();
            $containertag = '<input type="hidden" name="folderpath" value="" />';    my ($upload_result,$upload_output);
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';    if ($allowed) {
        }        if (($env{'form.uploaddoc.filename'}) &&
     ($env{'form.cmd'}=~/^upload_(\w+)/)) {
        $r->print(<<ENDCOURSEVERIFY);  # Process file upload - phase one - upload and parse primary file.  
 <form name="renameform" method="post" action="/adm/coursedocs">    undef($hadchanges);
 <input type="hidden" name="title" />            $upload_result = &process_file_upload(\$upload_output,$coursenum,
 <input type="hidden" name="cmd" />   $coursedom,\%allfiles,
 <input type="hidden" name="markcopy" />   \%codebase,$1);
 $containertag    if ($hadchanges) {
 </form>        &mark_hash_old();
 <form name="simpleedit" method="post" action="/adm/coursedocs">    }
 <input type="hidden" name="importdetail" value="" />            if ($upload_result eq 'phasetwo') {
 $uploadtag                $r->print($upload_output);
 </form>            }
 <form action="/adm/coursedocs" method="post" name="courseverify">        } elsif ($env{'form.phasetwo'}) {
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">            my %newname = ();
 <tr><td bgcolor="#DDDDCC">            my %origname = ();
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}            my %attribs = ();
 </td><td bgcolor="#DDDDCC">            my $updateflag = 0;
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}            my $residx = $env{'form.newidx'};
 $dumpbut            my $primary_url = &unescape($env{'form.primaryurl'});
 $exportbut  # Process file upload - phase two - gather secondary files.
 </td><td bgcolor="#DDDDCC">            for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
     <input type="submit" name="listsymbs" value="$lt{'ls'}" />                if ($env{'form.embedded_item_'.$i.'.filename'}) {
 </td><td bgcolor="#DDDDCC">                    my $javacodebase;
     <input type="hidden" name="folder" value="$env{'form.folder'}" />                    $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
     <input type="submit" name="docslog" value="$lt{'sl'}" />                    $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
 </td></tr></table>                    if (exists($env{'form.embedded_codebase_'.$i})) {
 </form>                        $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
 ENDCOURSEVERIFY                        $origname{$i} =~ s#^\Q$javacodebase\E/##;
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',                    }
      &mt('Editing the Table of Contents for your '.$type)));                    my @attributes = ();
     }                    if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
 # --------------------------------------------------------- Standard documents                        @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');                    } else {
     if (($standard) && ($allowed) && (!$forcesupplement)) {                        @attributes = ($env{'form.embedded_attrib_'.$i});
  $r->print('<tr><td bgcolor="#BBBBBB">');                    }
 #  '<h2>'.&mt('Main Course Documents').                    foreach my $attr (@attributes) {
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');                        push(@{$attribs{$i}},&unescape($attr));
        my $folder=$env{'form.folder'};                    }
        if ($folder eq '' || $folder eq 'supplemental') {                    if ($javacodebase) {
            $folder='default';                        $codebase{$i} = $javacodebase;
    $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));                        $codebase{$i} =~ s#/$##;
        }                        $updateflag = 1;
        my $postexec='';                    }
        if ($folder eq 'default') {                }
    $r->print('<script>this.window.name="loncapaclient";</script>');                unless ($newname{$i} eq $origname{$i}) {
        } else {                    $updateflag = 1;
            #$postexec='self.close();';                }
        }            }
        $hadchanges=0;  # Process file upload - phase three - modify primary file
        &editor($r,$coursenum,$coursedom,$folder,$allowed,$upload_output);            if ($updateflag) {
        if ($hadchanges) {                my ($content,$rtncode);
    &mark_hash_old()                my $updateflag = 0;
        }                my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
        &changewarning($r,$postexec);                if ($getstatus eq 'ok') {
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.                    foreach my $item (keys(%newname)) {
                      '.sequence';                        if ($newname{$item} ne $origname{$item}) {
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.                            my $attrib_regexp = '';
                      '.page';                            if (@{$attribs{$item}} > 1) {
  my $container='sequence';                                $attrib_regexp = join('|',@{$attribs{$item}});
  if ($env{'form.pagepath'}) {                            } else {
     $container='page';                                $attrib_regexp = $attribs{$item}[0];
  }                            }
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;                            if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
        $r->print(<<ENDFORM);                            }
 <table cellspacing=4 cellpadding=4><tr>                            $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>                        }
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>                        if (exists($codebase{$item})) {
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>                            $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
 </tr>                        }
 <tr><td bgcolor="#DDDDDD">                    }
 $lt{'file'}:<br />  # Save edited file.
 <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">                    my $saveresult;
 <input type="file" name="uploaddoc" size="40">                    my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 <br />                    my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 $lt{'title'}:<br />                    my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
 <input type="text" size="50" name="comment">                } else {
 $uploadtag                    &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
 <input type="hidden" name="cmd" value="upload_default">                }
 <br />            }
 <nobr>        }
 <label>$lt{'parse'}?    }
 <input type="checkbox" name="parserflag" />  
 </label>    unless ($showdoc ||  $upload_result eq 'phasetwo') {
 </nobr>  # -----------------------------------------------------------------------------
 <br />         my %lt=&Apache::lonlocal::texthash(
 <br />                  'uplm' => 'Upload a new main '.lc($type).' document',
 <nobr>                  'upls' => 'Upload a new supplemental '.lc($type).' document',
 <input type="submit" value="$lt{'upld'}">                  'impp' => 'Import a document',
  $help{'Uploading_From_Harddrive'}                  'pubd' => 'Published Documents',
 </nobr>   'copm' => 'All documents out of a published map into this folder',
 </form>                  'upld' => 'Upload Document',
 </td>                  'srch' => 'Search',
 <td bgcolor="#DDDDDD">                  'impo' => 'Import',
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">   'book' => 'Import Bookmarks',
 $lt{'pubd'}<br />                  'selm' => 'Select Map',
 $uploadtag                  'load' => 'Load Map',
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}" />                  'reco' => 'Recover Deleted Resources',
 <br />                  'newf' => 'New Folder',
 <nobr>                  'newp' => 'New Composite Page',
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}" />                  'extr' => 'External Resource',
 $help{'Importing_LON-CAPA_Resource'}                  'syll' => 'Syllabus',
 </nobr>                  'navc' => 'Navigate Contents',
 <br />                  'sipa' => 'Simple Page',
 <input type=button onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />                  'sipr' => 'Simple Problem',
 <p>                  'drbx' => 'Drop Box',
 <hr />                  'scuf' => 'Score Upload Form',
 $lt{'copm'}<br />                  'bull' => 'Bulletin Board',
 <input type="text" size="40" name="importmap"><br />                  'mypi' => 'My Personal Info',
 <nobr><input type=button                   'grpo' => 'Group Files',
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"                  'rost' => 'Course Roster',
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">   'abou' => 'About User',
 $help{'Load_Map'}</nobr>                  'imsf' => 'Import IMS package',
 </p>                  'file' =>  'File',
 </form>                  'title' => 'Title',
 <hr />                  'comment' => 'Comment',
 <form action="/adm/groupsort" method="post" name="recover">                  'parse' => 'Upload embedded images/multimedia files if HTML file!',
 <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1,0)" value="$lt{'reco'}" />   'nd' => 'New Document',
 </form>   'pm' => 'Published Map',
 ENDFORM   'sd' => 'Special Document',
        unless ($env{'form.pagepath'}) {   'mo' => 'More Options',
    $r->print(<<ENDFORM);   'hao' => 'Hide all Options'
 <hr />    );
 <form action="/adm/coursedocs" method="post" name="newext">  # -----------------------------------------------------------------------------
 $uploadtag   my $fileupload=(<<FIUP);
 <input type="hidden" name="importdetail" value="" />   $lt{'file'}:<br />
 <nobr>   <input type="file" name="uploaddoc" size="40" />
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"  FIUP
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}  
 </nobr>   my $checkbox=(<<CHBO);
 </form>   <!-- <label>$lt{'parse'}?
 <br /><form action="/adm/imsimportdocs" method="post" name="ims">   <input type="checkbox" name="parserflag" />
 <input type="hidden" name="folder" value="$folder" />   </label> -->
 <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />   <label>
 </nobr>   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 </form>   </label>
 ENDFORM  CHBO
        }  
        $r->print('</td><td bgcolor="#DDDDDD">');   my $fileuploadform=(<<FUFORM);
        unless ($env{'form.pagepath'}) {   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
            $r->print(<<ENDFORM);   $fileupload
 <br /><form action="/adm/coursedocs" method="post" name="newfolder">   <br />
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   $lt{'title'}:<br />
 <input type="hidden" name="importdetail" value="" />   <input type="text" size="50" name="comment" />
 <nobr>   $uploadtag
 <input name="newfolder" type="button"   <input type="hidden" name="cmd" value="upload_default" />
 onClick="javascript:makenewfolder(this.form,'$folderseq');"   <br />
 value="$lt{'newf'}" />$help{'Adding_Folders'}   <span class="LC_nobreak">
 </nobr>   $checkbox
 </form>   </span>
 <br /><form action="/adm/coursedocs" method="post" name="newpage">   <br />
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   <br />
 <input type="hidden" name="importdetail" value="" />   <span class="LC_nobreak">
 <nobr>   <input type="submit" value="$lt{'upld'}" />
 <input name="newpage" type="button"   $help{'Uploading_From_Harddrive'}
 onClick="javascript:makenewpage(this.form,'$pageseq');"   </span>
 value="$lt{'newp'}" />$help{'Adding_Pages'}   </form>
 </nobr>  FUFORM
 </form>  
 <br /><form action="/adm/coursedocs" method="post" name="newsyl">   my $simpleeditdefaultform=(<<SEDFFORM);
 $uploadtag   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
 <input type="hidden" name="importdetail"    $lt{'pubd'}<br />
 value="Syllabus=/public/$coursedom/$coursenum/syllabus" />   $uploadtag
 <nobr>   <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
 <input name="newsyl" type="submit" value="$lt{'syll'}" />    <br />
  $help{'Syllabus'}   <span class="LC_nobreak">
 </nobr>   <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
 </form>   $help{'Importing_LON-CAPA_Resource'}
 <br /><form action="/adm/coursedocs" method="post" name="newnav">   </span>
 $uploadtag   <br />
 <input type="hidden" name="importdetail"    <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
 value="Navigate Content=/adm/navmaps" />   <hr />
 <nobr>   <p>
 <input name="newnav" type="submit" value="$lt{'navc'}" />   $lt{'copm'}<br />
 $help{'Navigate_Content'}   <input type="text" size="40" name="importmap" /><br />
 </nobr>   <span class="LC_nobreak"><input type="button"
 </form>   onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
 <br /><form action="/adm/coursedocs" method="post" name="newsmppg">   value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
 $uploadtag   $help{'Load_Map'}</span>
 <input type="hidden" name="importdetail" value="" />   </p>
 <nobr>   </form>
 <input name="newsmppg" type="button" value="$lt{'sipa'}"  SEDFFORM
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}  
 </nobr>   my $extresourcesform=(<<ERFORM);
 </form>   <form action="/adm/coursedocs" method="post" name="newext">
 <br /><form action="/adm/coursedocs" method="post" name="newsmpproblem">   $uploadtag
 $uploadtag   <input type="hidden" name="importdetail" value="" />
 <input type="hidden" name="importdetail" value="" />   <span class="LC_nobreak">
 <nobr>   <input name="newext" type="button" onClick="javascript:makenewext('newext');"
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"   value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}   </span>
 </nobr>   </form>
 </form>  ERFORM
 <br /><form action="/adm/coursedocs" method="post" name="newdropbox">  
 $uploadtag            if ($allowed) {
 <input type="hidden" name="importdetail" value="" />   &update_paste_buffer($coursenum,$coursedom);
 <nobr>                   my $dumpbut=&dumpbutton();
 <input name="newdropbox" type="button" value="$lt{'drbx'}"         my $exportbut=&exportbutton();
 onClick="javascript:makedropbox();" />         my %lt=&Apache::lonlocal::texthash(
 </nobr>            'vc' => 'Verify Content',
 </form>    'cv' => 'Check/Set Resource Versions',
 <br /><form action="/adm/coursedocs" method="post" name="newexamupload">   'ls' => 'List Symbs',
 $uploadtag                                           'sl' => 'Show Log'
 <input type="hidden" name="importdetail" value="" />    );
 <nobr>  
 <input name="newexamupload" type="button" value="$lt{'scuf'}"         my $folderpath=$env{'form.folderpath'};
 onClick="javascript:makeexamupload();" />         if (!$folderpath) {
 $help{'Score_Upload_Form'}     if ($env{'form.folder'} eq '' ||
 </nobr>         $env{'form.folder'} eq 'supplemental') {
 </form>         $folderpath='default&'.
 <br /><form action="/adm/coursedocs" method="post" name="newbul">     &escape(&mt('Main '.$type.' Documents'));
 $uploadtag     }
 <input type="hidden" name="importdetail" value="" />         }
 <nobr>         unless ($env{'form.pagepath'}) {
 <input name="newbulletin" type="button" value="$lt{'bull'}"             $containertag = '<input type="hidden" name="folderpath" value="" />';
 onClick="javascript:makebulboard();" />             $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
 $help{'Bulletin Board'}         }
 </nobr>  
 </form>         $r->print(<<ENDCOURSEVERIFY);
 <br /><form action="/adm/coursedocs" method="post" name="newaboutme">  <form name="renameform" method="post" action="/adm/coursedocs">
 $uploadtag    <input type="hidden" name="title" />
 <input type="hidden" name="importdetail"     <input type="hidden" name="cmd" />
 value="$plainname=/adm/$udom/$uname/aboutme" />    <input type="hidden" name="markcopy" />
 <nobr>    <input type="hidden" name="copyfolder" />
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />    $containertag
 $help{'My Personal Info'}  </form>
 </nobr>  <form name="simpleedit" method="post" action="/adm/coursedocs">
 </form>    <input type="hidden" name="importdetail" value="" />
 <br /><form action="/adm/coursedocs" method="post" name="newaboutsomeone">    $uploadtag
 $uploadtag  </form>
 <input type="hidden" name="importdetail" value="" />  <form action="/adm/coursedocs" method="post" name="courseverify">
 <nobr>    <div class="LC_docs_course_commands">
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"   
 onClick="javascript:makeabout();" />        <div>
 </nobr>          <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}
 </form>        </div>
 <br /><form action="/adm/coursedocs" method="post" name="newgroupfiles">        <div>
 $uploadtag          <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}
 <input type="hidden" name="importdetail"        </div>
 value="Group Files=/adm/$coursedom/$coursenum/aboutme" />          $dumpbut
 <nobr>          $exportbut
 <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />        <div>
 $help{'Group Files'}          <input type="submit" name="listsymbs" value="$lt{'ls'}" />
 </nobr>        </div>
 </form>        <div>
 ENDFORM          <input type="hidden" name="folder" value="$env{'form.folder'}" />
        }          <input type="submit" name="docslog" value="$lt{'sl'}" />
        if ($env{'form.pagepath'}) {        </div>
            $r->print(<<ENDBLOCK);    </div>
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">  </form>
 $uploadtag  <div style="clear: both; height: 0px;">&nbsp;</div>
 <input type="hidden" name="importdetail" value="" />  ENDCOURSEVERIFY
 <nobr>         $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"       &mt('Editing the Table of Contents for your '.$type)));
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      }
 </nobr>  # --------------------------------------------------------- Standard documents
 </form>      $r->print('<table class="LC_docs_documents">');
 <br /><form action="/adm/coursedocs" method="post" name="newexamupload">  
 $uploadtag      if (($standard) && ($allowed) && (!$forcesupplement)) {
 <input type="hidden" name="importdetail" value="" />   $r->print('<tr><td class="LC_docs_document">');
 <nobr>  #  '<h2>'.&mt('Main Course Documents').
 <input name="newexamupload" type="button" value="$lt{'scuf'}"  #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');
 onClick="javascript:makeexamupload();" />         my $folder=$env{'form.folder'};
 $help{'Score_Upload_Form'}         if ($folder eq '' || $folder eq 'supplemental') {
 </nobr>             $folder='default';
 </form>     $env{'form.folderpath'}='default&'.&escape(&mt('Main '.$type.' Documents'));
 ENDBLOCK             $uploadtag = '<input type="hidden" name="folderpath" value="'.
        }         &HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />';
        $r->print('</td></tr>'."\n".         }
 '</table>');         my $postexec='';
        $r->print('</td></tr>');         if ($folder eq 'default') {
     }     $r->print('<script type="text/javascript">this.window.name="loncapaclient";</script>');
 # ----------------------------------------------------- Supplemental documents         } else {
     if (!$forcestandard) {             #$postexec='self.close();';
        $r->print('<tr><td bgcolor="#BBBBBB">');         }
 # '<h2>'.&mt('Supplemental Course Documents').         $hadchanges=0;
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');         my $error = &editor($r,$coursenum,$coursedom,$folder,$allowed,
        my $folder=$env{'form.folder'};     $upload_output,$type);
        unless ($folder=~/^supplemental/) {         if ($error) {
    $folder='supplemental';     $r->print('<p><span class="LC_error">'.$error.'</span></p>');
        }         }
        if ($folder =~ /^supplemental$/ &&         if ($hadchanges) {
    $env{'form.folderpath'} =~ /^default\&/) {     &mark_hash_old();
    $env{'form.folderpath'}='supplemental&'.         }
        &escape(&mt('Supplemental '.$type.' Documents'));         &changewarning($r,$postexec);
        }         my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
        &editor($r,$coursenum,$coursedom,$folder,$allowed);                       '.sequence';
        if ($allowed) {         my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.
        my $folderseq=                       '.page';
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.   my $container='sequence';
                      '.sequence';   if ($env{'form.pagepath'}) {
       $container='page';
           $r->print(<<ENDSUPFORM);   }
 <table cellspacing=4 cellpadding=4><tr>   my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>  
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>  
 </tr>  
 <tr><td bgcolor="#DDDDDD">   my $recoverform=(<<RFORM);
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">   <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'}" />
 <br />   </form>
 <br />  RFORM
 <nobr>  
 <label>$lt{'parse'}?   my $imspform=(<<IMSPFORM);
 <input type="checkbox" name="parserflag" />   <form action="/adm/imsimportdocs" method="post" name="ims">
 </label>   <input type="hidden" name="folder" value="$folder" />
 </nobr>   <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />
 <br /><br />   </form>
 $lt{'comment'}:<br />  IMSPFORM
 <textarea cols=50 rows=4 name='comment'>  
 </textarea>   my $newnavform=(<<NNFORM);
 <br />   <form action="/adm/coursedocs" method="post" name="newnav">
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   $uploadtag
 <input type="hidden" name="cmd" value="upload_supplemental">   <input type="hidden" name="importdetail"
 <nobr>   value="$lt{'navc'}=/adm/navmaps" />
 <input type="submit" value="$lt{'upld'}">   <span class="LC_nobreak">
  $help{'Uploading_From_Harddrive'}   <input name="newnav" type="submit" value="$lt{'navc'}" />
 </nobr>   $help{'Navigate_Content'}
 </form>   </span>
 </td>   </form>
 <td bgcolor="#DDDDDD">  NNFORM
 <form action="/adm/coursedocs" method="post" name="supnewfolder">   my $newsmppageform=(<<NSPFORM);
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   <form action="/adm/coursedocs" method="post" name="newsmppg">
 <input type="hidden" name="importdetail" value="" />   $uploadtag
 <nobr>   <input type="hidden" name="importdetail" value="" />
 <input name="newfolder" type="button"   <span class="LC_nobreak">
 onClick="javascript:makenewfolder(this.form,'$folderseq');"   <input name="newsmppg" type="button" value="$lt{'sipa'}"
 value="$lt{'newf'}" /> $help{'Adding_Folders'}   onClick="javascript:makesmppage();" /> $help{'Simple Page'}
 </nobr>   </span>
 </form>   </form>
 <br /><form action="/adm/coursedocs" method="post" name="supnewext">  NSPFORM
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  
 <input type="hidden" name="importdetail" value="" />   my $newsmpproblemform=(<<NSPROBFORM);
 <nobr>   <form action="/adm/coursedocs" method="post" name="newsmpproblem">
 <input name="newext" type="button"    $uploadtag
 onClick="javascript:makenewext('supnewext');"   <input type="hidden" name="importdetail" value="" />
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   <span class="LC_nobreak">
 </nobr>   <input name="newsmpproblem" type="button" value="$lt{'sipr'}"
 </form>   onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}
 <br /><form action="/adm/coursedocs" method="post" name="supnewsyl">   </span>
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   </form>
 <input type="hidden" name="importdetail"   
 value="Syllabus=/public/$coursedom/$coursenum/syllabus" />  NSPROBFORM
 <nobr>  
 <input name="newsyl" type="submit" value="$lt{'syll'}" />   my $newdropboxform=(<<NDBFORM);
 $help{'Syllabus'}   <form action="/adm/coursedocs" method="post" name="newdropbox">
 </nobr>   $uploadtag      
 </form>   <input type="hidden" name="importdetail" value="" />
 <br /><form action="/adm/coursedocs" method="post" name="subnewaboutme">   <span class="LC_nobreak">          
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   <input name="newdropbox" type="button" value="$lt{'drbx'}"
 <input type="hidden" name="importdetail"    onClick="javascript:makedropbox();" />
 value="$plainname=/adm/$udom/$uname/aboutme" />   </span>        
 <nobr>   </form>
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />  NDBFORM
 $help{'My Personal Info'}  
 </nobr>   my $newexuploadform=(<<NEXUFORM);
 </form>   <form action="/adm/coursedocs" method="post" name="newexamupload">
 </td></tr>   $uploadtag
 </table></td></tr>   <input type="hidden" name="importdetail" value="" />
 ENDSUPFORM   <span class="LC_nobreak">
        }   <input name="newexamupload" type="button" value="$lt{'scuf'}"
     }   onClick="javascript:makeexamupload();" />
     if ($allowed) {   $help{'Score_Upload_Form'}
  $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>');   </span>
     }   </form>
     $r->print('</table>');  NEXUFORM
   } else {  
       unless ($upload_result eq 'phasetwo') {   my $newbulform=(<<NBFORM);
 # -------------------------------------------------------- This is showdoc mode   <form action="/adm/coursedocs" method="post" name="newbul">
           $r->print("<h1>".&mt('Uploaded Document').' - '.   $uploadtag
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.   <input type="hidden" name="importdetail" value="" />
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".   <span class="LC_nobreak">
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');   <input name="newbulletin" type="button" value="$lt{'bull'}"
       }   onClick="javascript:makebulboard();" />
   }   $help{'Bulletin Board'}
  }   </span>
  $r->print(&Apache::loncommon::end_page());   </form>
  return OK;  NBFORM
 }   
    my $newaboutmeform=(<<NAMFORM);
    <form action="/adm/coursedocs" method="post" name="newaboutme">
 sub editing_js {   $uploadtag
     my ($udom,$uname) = @_;   <input type="hidden" name="importdetail"
     my $now = time();   value="$plainname=/adm/$udom/$uname/aboutme" />
    <span class="LC_nobreak">
     return <<ENDNEWSCRIPT;   <input name="newaboutme" type="submit" value="$lt{'mypi'}" />
 function makenewfolder(targetform,folderseq) {   $help{'My Personal Info'}
     var foldername=prompt('Name of New Folder','New Folder');   </span>
     if (foldername) {   </form>
        targetform.importdetail.value=escape(foldername)+"="+folderseq;  NAMFORM
         targetform.submit();  
     }   my $newaboutsomeoneform=(<<NASOFORM);
 }   <form action="/adm/coursedocs" method="post" name="newaboutsomeone">
    $uploadtag
 function makenewpage(targetform,folderseq) {   <input type="hidden" name="importdetail" value="" />
     var pagename=prompt('Name of New Page','New Page');   <span class="LC_nobreak">
     if (pagename) {   <input name="newaboutsomeone" type="button" value="$lt{'abou'}"
         targetform.importdetail.value=escape(pagename)+"="+folderseq;   onClick="javascript:makeabout();" />
         targetform.submit();   </span>
     }   </form>
 }  NASOFORM
   
 function makenewext(targetname) {  
     this.document.forms.extimport.useform.value=targetname;   my $newrosterform=(<<NROSTFORM);
     window.open('/adm/rat/extpickframe.html');   <form action="/adm/coursedocs" method="post" name="newroster">
 }   $uploadtag
    <input type="hidden" name="importdetail"
 function makeexamupload() {   value="$lt{'rost'}=/adm/viewclasslist" />
    var title=prompt('Listed Title for the Uploaded Score');   <span class="LC_nobreak">
    if (title) {    <input name="newroster" type="submit" value="$lt{'rost'}" />
     this.document.forms.newexamupload.importdetail.value=   $help{'Course Roster'}
  escape(title)+'=/res/lib/templates/examupload.problem';   </span>
     this.document.forms.newexamupload.submit();   </form>
    }  NROSTFORM
 }  
          $r->print(<<ENDFORM);
 function makesmppage() {  
    var title=prompt('Listed Title for the Page');  <ul class="LC_TabContent">
    if (title) {   <li>$lt{'nd'}</li>
     this.document.forms.newsmppg.importdetail.value=  <li>$lt{'pm'}</li>
  escape(title)+'=/adm/$udom/$uname/$now/smppg';  <li>$lt{'pubd'}</li>
     this.document.forms.newsmppg.submit();  <li>$lt{'sd'}</li>
    }  <li>$lt{'mo'}</li>
 }  <li>$lt{'hao'}</li>
   </ul>
 function makesmpproblem() {  
    var title=prompt('Listed Title for the Problem');  <table class="LC_docs_adddocs">
    if (title) {   <!-- <tr>
     this.document.forms.newsmpproblem.importdetail.value=  <th>$lt{'uplm'}</th>
  escape(title)+'=/res/lib/templates/simpleproblem.problem';  <th>$lt{'impp'}</th>
     this.document.forms.newsmpproblem.submit();  <th>$lt{'spec'}</th>
    }  </tr> -->
 }  <tr>
   <td>
 function makedropbox() {  $fileuploadform
    var title=prompt('Listed Title for the Drop Box');  </td>
    if (title) {   <td>
     this.document.forms.newdropbox.importdetail.value=  $simpleeditdefaultform
         escape(title)+'=/res/lib/templates/DropBox.problem';  <hr />
     this.document.forms.newdropbox.submit();  $recoverform
    }  ENDFORM
 }         unless ($env{'form.pagepath'}) {
      $r->print(<<ENDFORM);
 function makebulboard() {  <hr />
    var title=prompt('Listed Title for the Bulletin Board');  $extresourcesform
    if (title) {   <br />
     this.document.forms.newbul.importdetail.value=  $imspform
  escape(title)+'=/adm/$udom/$uname/$now/bulletinboard';  ENDFORM
     this.document.forms.newbul.submit();         }
    }         $r->print('</td><td>');
 }         unless ($env{'form.pagepath'}) {
      my $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
 function makeabout() {  
    var user=prompt("Enter user:domain for User's 'About Me' Page");  
    if (user) {  
        var comp=new Array();   my $newpageform=(<<NPFORM);
        comp=user.split(':');   <form action="/adm/coursedocs" method="post" name="newpage">
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {   <input type="hidden" name="folderpath" value="$path" />
    if ((comp[0]) && (comp[1])) {   <input type="hidden" name="importdetail" value="" />
        this.document.forms.newaboutsomeone.importdetail.value=   <span class="LC_nobreak">
    'About '+escape(user)+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';   <input name="newpage" type="button"
        this.document.forms.newaboutsomeone.submit();   onClick="javascript:makenewpage(this.form,'$pageseq');"
    } else {   value="$lt{'newp'}" />$help{'Adding_Pages'}
                alert("Not a valid user:domain");   </span>
            }   </form>
        } else {  NPFORM
            alert("Please enter both user and domain in the format user:domain");   
        }   my $newfolderform=(<<NFFORM);
    }   <form action="/adm/coursedocs" method="post" name="newfolder">
 }   <input type="hidden" name="folderpath" value="$path" />
    <input type="hidden" name="importdetail" value="" />
 function makeims() {   <span class="LC_nobreak">
     var caller = document.forms.ims.folder.value;   <input name="newfolder" type="button"
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";   onClick="javascript:makenewfolder(this.form,'$folderseq');"
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");   value="$lt{'newf'}" />$help{'Adding_Folders'}
     newWindow.location.href = newlocation;   </span>
 }   </form>
   NFFORM
   
 function finishpick() {   my $newsylform=(<<NSYLFORM);
     var title=this.document.forms.extimport.title.value;   <form action="/adm/coursedocs" method="post" name="newsyl">
     var url=this.document.forms.extimport.url.value;   $uploadtag
     var form=this.document.forms.extimport.useform.value;   <input type="hidden" name="importdetail"
     eval   value="$lt{'syll'}=/public/$coursedom/$coursenum/syllabus" />
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+   <span class="LC_nobreak">
     '";this.document.forms.'+form+'.submit();');   <input name="newsyl" type="submit" value="$lt{'syll'}" />
 }   $help{'Syllabus'}
    </span>
 function changename(folderpath,index,oldtitle,container,pagesymb) {   </form>
     var title=prompt('New Title',oldtitle);  NSYLFORM
     if (title) {  
  this.document.forms.renameform.title.value=title;   my $newgroupfileform=(<<NGFFORM);
  this.document.forms.renameform.cmd.value='rename_'+index;   <form action="/adm/coursedocs" method="post" name="newgroupfiles">
         if (container == 'sequence') {   $uploadtag
     this.document.forms.renameform.folderpath.value=folderpath;   <input type="hidden" name="importdetail"
         }   value="$lt{'grpo'}=/adm/$coursedom/$coursenum/aboutme" />
         if (container == 'page') {   <span class="LC_nobreak">
             this.document.forms.renameform.pagepath.value=folderpath;   <input name="newgroupfiles" type="submit" value="$lt{'grpo'}" />
             this.document.forms.renameform.pagesymb.value=pagesymb;   $help{'Group Files'}
         }   </span>
         this.document.forms.renameform.submit();   </form>
     }  NGFFORM
 }  
   
 function removeres(folderpath,index,oldtitle,container,pagesymb) {             $r->print(<<ENDFORM);
     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {  <br />
  this.document.forms.renameform.cmd.value='del_'+index;  $newfolderform
         if (container == 'sequence') {  <br />
             this.document.forms.renameform.folderpath.value=folderpath;  $newpageform
         }  <br />
         if (container == 'page') {  $newsylform
             this.document.forms.renameform.pagepath.value=folderpath;  <br />
             this.document.forms.renameform.pagesymb.value=pagesymb;  $newnavform
         }  <br />
         this.document.forms.renameform.submit();  $newsmppageform
     }  <br />
 }  $newsmpproblemform
   <br />
 function cutres(folderpath,index,oldtitle,container,pagesymb) {  $newdropboxform
     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;  $newexuploadform
  this.document.forms.renameform.markcopy.value=index;  <br />
         if (container == 'sequence') {  $newbulform
             this.document.forms.renameform.folderpath.value=folderpath;  <br />
         }  $newaboutmeform
         if (container == 'page') {  <br />
             this.document.forms.renameform.pagepath.value=folderpath;  $newaboutsomeoneform
             this.document.forms.renameform.pagesymb.value=pagesymb;  <br />
         }  $newgroupfileform
         this.document.forms.renameform.submit();  <br />
     }  $newrosterform
 }  ENDFORM
          }
 function markcopy(folderpath,index,oldtitle,container,pagesymb) {         if ($env{'form.pagepath'}) {
     this.document.forms.renameform.markcopy.value=index;             $r->print(<<ENDBLOCK);
     if (container == 'sequence') {  $newsmpproblemform
  this.document.forms.renameform.folderpath.value=folderpath;  <br />
     }  $newexuploadform
     if (container == 'page') {  ENDBLOCK
  this.document.forms.renameform.pagepath.value=folderpath;         }
  this.document.forms.renameform.pagesymb.value=pagesymb;         $r->print('</td></tr>'."\n".
     }  '</table>');
     this.document.forms.renameform.submit();         $r->print('</td></tr>');
 }      }
   # ----------------------------------------------------- Supplemental documents
 ENDNEWSCRIPT      if (!$forcestandard) {
 }         $r->print('<tr><td class="LC_docs_document">');
 1;  # '<h2>'.&mt('Supplemental Course Documents').
 __END__  #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');
          my $folder=$env{'form.folder'};
          unless ($folder=~/^supplemental/) {
      $folder='supplemental';
          }
          if ($folder =~ /^supplemental$/ &&
      (($env{'form.folderpath'} =~ /^default\&/) || ($env{'form.folderpath'} eq ''))) {
             $env{'form.folderpath'} = 'supplemental&'.
                                       &escape(&mt('Supplemental '.$type.' Documents'));
          }
          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.275  
changed lines
  Added in v.1.326


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