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

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

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


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