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

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

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


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