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

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

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


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