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

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


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