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

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


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