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

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

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


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