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

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


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