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

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


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