Diff for /loncom/interface/londocs.pm between versions 1.172 and 1.327

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

Removed from v.1.172  
changed lines
  Added in v.1.327


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