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

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

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


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