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

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


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