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

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


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