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

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


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