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

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

Removed from v.1.303  
changed lines
  Added in v.1.326


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