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

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

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


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