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

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

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


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