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

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

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


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