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

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

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


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