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

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


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