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

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


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