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

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

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


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