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

version 1.206, 2005/09/20 07:52:03 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[$_]);     
            unless ($name) {  $name=(split(/\//,$url))[-1]; }      return if ($fatal);
            unless ($name) { $idx++; next; }  
            $r->print(&entryline($idx,$name,$url,$folder,$allowed,$_,$coursenum));  # Mark for copying
            $idx++;      my ($title,$url)=split(':',$LONCAPA::map::resources[$LONCAPA::map::order[$env{'form.markcopy'}]]);
    $shown++;      if (&is_supplemental_title($title)) {
         }          &Apache::lonnet::appenv({'docs.markedcopy_supplemental' => $title});
  unless ($shown) {   ($title) = &parse_supplemental_title($title);
     $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');      } elsif ($env{'docs.markedcopy_supplemental'}) {
  }          &Apache::lonnet::delenv('docs\\.markedcopy_supplemental');
         $r->print("\n</table>\n");      }
  if ($env{'form.markedcopy_url'}) {      $url=~s{http(&colon;|:)//https(&colon;|:)//}{https$2//};
     $r->print(<<ENDPASTE);  
 <p><form name="pasteform" action="/adm/coursedocs" method="post">      &Apache::lonnet::appenv({'docs.markedcopy_title' => $title,
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />      'docs.markedcopy_url'   => $url});
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      delete($env{'form.markcopy'});
 ENDPASTE  }
             $r->print(  
    '<input type="submit" name="pastemarked" value="'.&mt('Paste').  sub print_paste_buffer {
       '" /> '.&Apache::loncommon::filedescription(      my ($r,$container) = @_;
  (split(/\./,$env{'form.markedcopy_url'}))[-1]).': '.      return if (!defined($env{'docs.markedcopy_url'}));
       $env{'form.markedcopy_title'});  
             if ($container eq 'page') {      $r->print(<<ENDPASTE);
  $r->print(<<PAGEINFO);  <form name="pasteform" action="/adm/coursedocs" method="post"><p>
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />  ENDPASTE
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />      $r->print('<input type="submit" name="pastemarked" value="'.&mt('Paste').'" /> ');
 PAGEINFO  
             } else {      my $type;
  $r->print(<<FOLDERINFO);      if ($env{'docs.markedcopy_url'} =~ m{^(?:/adm/wrapper/ext|(?:http|https)(?:&colon;|:))//} ) {
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   $type = &mt('External Resource');
 FOLDERINFO   $r->print($type.': '.
     }    &LONCAPA::map::qtescape($env{'docs.markedcopy_title'}).' ('.
     $r->print('</form></p>');    &LONCAPA::map::qtescape($env{'docs.markedcopy_url'}).')');
  }      }  else {
     }   my $extension = (split(/\./,$env{'docs.markedcopy_url'}))[-1];
 }   my $icon = &Apache::loncommon::icon($extension);
    if ($extension eq 'sequence' &&
 sub process_file_upload {      $env{'docs.markedcopy_url'} =~ m{/default_\d+\.sequence$ }x) {
     my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;      $icon = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
 # upload a file, if present      $icon .= '/folder_closed.gif';
     my $parseaction;   }
    if ($env{'form.parserflag'}) {   $icon = '<img src="'.$icon.'" alt="" class="LC_icon" />';
         $parseaction = 'parse';   $r->print($icon.$type.': '.  &parse_supplemental_title(&LONCAPA::map::qtescape($env{'docs.markedcopy_title'})));
     }      }
     my $phase_status;      if ($container eq 'page') {
     my $folder=$env{'form.folder'};   $r->print('
     if ($folder eq '') {   <input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />
         $folder='default';   <input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />
     }  ');
     if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {      } else {
         my $errtext='';   $r->print('
         my $fatal=0;          <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
         my $container='sequence';  ');
         if ($env{'form.pagepath'}) {      }
             $container='page';      $r->print('</p></form>');
         }  }
         ($errtext,$fatal)=  
               &mapread($coursenum,$coursedom,$folder.'.'.$container);  sub do_paste_from_buffer {
         if ($#Apache::lonratedt::order<1) {      my ($coursenum,$coursedom,$folder) = @_;
             $Apache::lonratedt::order[0]=1;  
             $Apache::lonratedt::resources[1]='';      if (!$env{'form.pastemarked'}) {
         }          return;
         if ($fatal) {      }
             return 'failed';  
         }  # paste resource to end of list
         my $destination = 'docs/';      my $url=&LONCAPA::map::qtescape($env{'docs.markedcopy_url'});
         if ($folder =~ /^supplemental/) {      my $title=&LONCAPA::map::qtescape($env{'docs.markedcopy_title'});
             $destination = 'supplemental/';  # Maps need to be copied first
         }      if (($url=~/\.(page|sequence)$/) && ($url=~/^\/uploaded\//)) {
         if (($folder eq 'default') || ($folder eq 'supplemental')) {   $title=&mt('Copy of').' '.$title;
             $destination .= 'default/';   my $newid=$$.int(rand(100)).time;
         } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {   my ($oldid,$ext) = ($url=~/^(.+)\.(\w+)$/);
             $destination .=  $2.'/';          if ($oldid =~ m{^(/uploaded/\Q$coursedom\E/\Q$coursenum\E/)(\D+)(\d+)$}) {
         }              my $path = $1;
 # this is for a course, not a user, so set coursedoc flag              my $prefix = $2;
 # probably the only place in the system where this should be "1"              my $ancestor = $3;
         my $newidx=&Apache::lonratedt::getresidx();              if (length($ancestor) > 10) {
         $destination .= $newidx;                  $ancestor = substr($ancestor,-10,10);
         my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,              }
  $parseaction,$allfiles,              $oldid = $path.$prefix.$ancestor;
  $codebase);          }
         my $ext='false';          my $counter = 0;
         if ($url=~/^http\:\/\//) { $ext='true'; }          my $newurl=$oldid.$newid.'.'.$ext;
         $url=~s/\:/\&colon;/g;          my $is_unique = &uniqueness_check($newurl);
         my $comment=$env{'form.comment'};          while (!$is_unique && $counter < 100) {
         $comment=~s/\</\&lt\;/g;              $counter ++;
         $comment=~s/\>/\&gt\;/g;              $newid ++;
         $comment=~s/\:/\&colon;/g;              $newurl = $oldid.$newid;
         if ($folder=~/^supplemental/) {              $is_unique = &uniqueness_check($newurl);
               $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.          }
                   $env{'user.domain'}.'___&&&___'.$comment;          if (!$is_unique) {
         }              if ($url=~/\.page$/) {
                   return &mt('Paste failed: an error occurred creating a unique URL for the composite page');
         $Apache::lonratedt::resources[$newidx]=              } else {
                   $comment.':'.$url.':'.$ext.':normal:res';                  return &mt('Paste failed: an error occurred creating a unique URL for the folder');
         $Apache::lonratedt::order[$#Apache::lonratedt::order+1]= $newidx;              }
         ($errtext,$fatal)=&storemap($coursenum,$coursedom,          }
     $folder.'.'.$container);   my $storefn=$newurl;
         if ($fatal) {   $storefn=~s{^/\w+/$match_domain/$match_username/}{};
             $$upload_output .= '<p><font color="red">'.$errtext.'</font></p>';   my $paste_map_result =
             return 'failed';              &Apache::lonclonecourse::writefile($env{'request.course.id'},$storefn,
         } else {         &Apache::lonnet::getfile($url));
             if ($parseaction eq 'parse') {          if ($paste_map_result eq '/adm/notfound.html') {
                 my $total_embedded = keys(%{$allfiles});              if ($url=~/\.page$/) {
                 if ($total_embedded > 0) {                  return &mt('Paste failed: an error occurred saving the composite page');
                     my $num = 0;              } else {
                     $$upload_output .= 'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />                  return &mt('Paste failed: an error occurred saving the folder');
    <form name="upload_embedded" action="/adm/coursedocs"              }
                   method="post" enctype="multipart/form-data">          }
    <input type="hidden" name="folderpath" value="'.$env{'form.folderpath'}.'" />   <input type="hidden" name="cmd" value="upload_embedded" />   $url = $newurl;
    <input type="hidden" name="newidx" value="'.$newidx.'" />      }
    <input type="hidden" name="primaryurl" value="'.&Apache::lonnet::escape($url).'" />  # published maps can only exists once, so remove it from paste buffer when done
    <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';      if (($url=~/\.(page|sequence)$/) && ($url=~m {^/res/})) {
                     $$upload_output .= '<b>Upload embedded files</b>:<br />   &Apache::lonnet::delenv('docs\\.markedcopy');
    <table>';      }
                     foreach my $embed_file (keys(%{$allfiles})) {      if ($url=~ m{/smppg$}) {
                         $$upload_output .= '<tr><td>'.$embed_file.   my $db_name = &Apache::lonsimplepage::get_db_name($url);
           '<input name="embedded_item_'.$num.'" type="file" />   if ($db_name =~ /^smppage_/) {
            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&Apache::lonnet::escape($embed_file).'" />';      #simple pages, need to copy the db contents to a new one.
                         my $attrib;      my %contents=&Apache::lonnet::dump($db_name,$coursedom,$coursenum);
                         if (@{$$allfiles{$embed_file}} > 1) {      my $now = time();
                             $attrib = join(':',@{$$allfiles{$embed_file}});      $db_name =~ s{_\d*$ }{_$now}x;
                         } else {      my $result=&Apache::lonnet::put($db_name,\%contents,
                             $attrib = $$allfiles{$embed_file}[0];      $coursedom,$coursenum);
                         }      $url =~ s{/(\d*)/smppg$ }{/$now/smppg}x;
                         $$upload_output .=      $title=&mt('Copy of').' '.$title;
            '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.$attrib.'" />';   }
                         if (exists($$codebase{$embed_file})) {      }
                             $$upload_output .=       $title = &LONCAPA::map::qtunescape($title);
           '<input name="codebase_'.$num.'" type="hidden" value="'.&Apache::lonnet::escape($$codebase{$embed_file}).'" />';      my $ext='false';
                         }      if ($url=~m{^http(|s)://}) { $ext='true'; }
                         $$upload_output .= '</td></tr>';      $url       = &LONCAPA::map::qtunescape($url);
                         $num ++;  # Now insert the URL at the bottom
                     }      my $newidx = &LONCAPA::map::getresidx($url);
                     $phase_status = 'phasetwo';      if ($env{'docs.markedcopy_supplemental'}) {
                     $$upload_output .= '</table><br />          if ($folder =~ /^supplemental/) {
    <input type ="submit" value="Complete upload" />              $title = $env{'docs.markedcopy_supplemental'};
    </form>';          } else {
                 } else {              (undef,undef,$title) =
                     $$upload_output .= 'No embedded items identified<br />';                  &parse_supplemental_title($env{'docs.markedcopy_supplemental'});
                 }          }
             }      } else {
         }          if ($folder=~/^supplemental/) {
     }             $title=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
     return $phase_status;                    $env{'user.domain'}.'___&&&___'.$title;
 }          }
       }
 sub process_secondary_uploads {  
     my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;      $LONCAPA::map::resources[$newidx]= $title.':'.$url.':'.$ext.':normal:res';
     my $folder=$env{'form.folder'};      push(@LONCAPA::map::order, $newidx);
     my $destination = 'docs/';      return 'ok';
     if ($folder =~ /^supplemental/) {  # Store the result
         $destination = 'supplemental/';  }
     }  
     if (($folder eq 'default') || ($folder eq 'supplemental')) {  sub uniqueness_check {
         $destination .= 'default/';      my ($newurl) = @_;
     } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {      my $unique = 1;
         $destination .=  $1.'/';      foreach my $res (@LONCAPA::map::order) {
     }          my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
     $destination .= $newidx;          $url=&LONCAPA::map::qtescape($url);
     my ($url,$filename);          if ($newurl eq $url) {
     $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);              $unique = 0;
     ($filename) = ($url =~ m-^/uploaded/$coursedom/$coursenum/$destination/(.+)$-);              last;    
     return $filename;          }
 }      }
       return $unique;
 # --------------------------------------------------------------- An entry line  }
   
 sub entryline {  my %parameter_type = ( 'randompick'     => 'int_pos',
     my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;         'hiddenresource' => 'string_yesno',
     $title=~s/\&colon\;/\:/g;         'encrypturl'     => 'string_yesno',
     $title=&HTML::Entities::encode(&HTML::Entities::decode(         'randomorder'    => 'string_yesno',);
      &Apache::lonnet::unescape($title)),'"<>&\'');  my $valid_parameters_re = join('|',keys(%parameter_type));
     my $renametitle=$title;  # set parameters
     my $foldertitle=$title;  sub update_parameter {
     my $pagetitle=$title;  
     my $orderidx=$Apache::lonratedt::order[$index];      return 0 if ($env{'form.changeparms'} !~ /^($valid_parameters_re)$/);
     if ($title=~ /^(\d+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(\w+)___&amp;&amp;&amp;___(.*)$/ ) {   
  $foldertitle=&Apache::lontexconvert::msgtexconverted($4);      my $which = $env{'form.changeparms'};
  $renametitle=$4;      my $idx = $env{'form.setparms'};
  $title='<i>'.&Apache::lonlocal::locallocaltime($1).'</i> '.      if ($env{'form.'.$which.'_'.$idx}) {
     &Apache::loncommon::plainname($2,$3).': <br />'.   my $value = ($which eq 'randompick') ? $env{'form.'.$which.'_'.$idx}
     $foldertitle;                                       : 'yes';
     }   &LONCAPA::map::storeparameter($idx, 'parameter_'.$which, $value,
     $renametitle=~s/\&quot\;/\\\"/g;        $parameter_type{$which});
     my $line='<tr>';   &remember_parms($idx,$which,'set',$value);
 # Edit commands      } else {
     my $container;   &LONCAPA::map::delparameter($idx,'parameter_'.$which);
     my $folderpath;  
     if ($env{'form.folderpath'}) {   &remember_parms($idx,$which,'del');
         $container = 'sequence';      }
  $folderpath=&Apache::lonnet::escape($env{'form.folderpath'});      return 1;
  # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');  }
     }  
     my ($pagepath,$pagesymb);  
     if ($env{'form.pagepath'}) {  sub handle_edit_cmd {
         $container = 'page';      my ($coursenum,$coursedom) =@_;
         $pagepath=&Apache::lonnet::escape($env{'form.pagepath'});  
         $pagesymb=&Apache::lonnet::escape($env{'form.pagesymb'});      my ($cmd,$idx)=split('_',$env{'form.cmd'});
     }  
     my $cpinfo='';      my $ratstr = $LONCAPA::map::resources[$LONCAPA::map::order[$idx]];
     if ($env{'form.markedcopy_url'}) {      my ($title, $url, @rrest) = split(':', $ratstr);
        $cpinfo='&markedcopy_url='.  
                &Apache::lonnet::escape($env{'form.markedcopy_url'}).      if ($cmd eq 'del') {
                '&markedcopy_title='.   if (($url=~m|/+uploaded/\Q$coursedom\E/\Q$coursenum\E/|) &&
                &Apache::lonnet::escape($env{'form.markedcopy_title'});      ($url!~/\.(page|sequence|problem|exam|quiz|assess|survey|form|library|task)$/)) {
     }      &Apache::lonnet::removeuploadedurl($url);
     if ($allowed) {   } else {
  my $incindex=$index+1;      &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
  my $selectbox='';   }
  if (($folder!~/^supplemental/) &&   splice(@LONCAPA::map::order, $idx, 1);
     ($#Apache::lonratedt::order>0) &&   
     ((split(/\:/,      } elsif ($cmd eq 'cut') {
      $Apache::lonratedt::resources[$Apache::lonratedt::order[0]]))[1]    &LONCAPA::map::makezombie($LONCAPA::map::order[$idx]);
      ne '') &&    splice(@LONCAPA::map::order, $idx, 1);
     ((split(/\:/,  
      $Apache::lonratedt::resources[$Apache::lonratedt::order[1]]))[1]       } elsif ($cmd eq 'up'
      ne '')) {       && ($idx) && (defined($LONCAPA::map::order[$idx-1]))) {
     $selectbox=   @LONCAPA::map::order[$idx-1,$idx] = @LONCAPA::map::order[$idx,$idx-1];
  '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.  
  '<select name="newpos" onChange="this.form.submit()">';      } elsif ($cmd eq 'down'
     for (my $i=1;$i<=$#Apache::lonratedt::order+1;$i++) {       && defined($LONCAPA::map::order[$idx+1])) {
  if ($i==$incindex) {   @LONCAPA::map::order[$idx+1,$idx] = @LONCAPA::map::order[$idx,$idx+1];
     $selectbox.='<option value="" selected="1">('.$i.')</option>';  
  } else {      } elsif ($cmd eq 'rename') {
     $selectbox.='<option value="'.$i.'">'.$i.'</option>';  
  }   my $comment = &LONCAPA::map::qtunescape($env{'form.title'});
     }   if ($comment=~/\S/) {
     $selectbox.='</select>';      $LONCAPA::map::resources[$LONCAPA::map::order[$idx]]=
  }   $comment.':'.join(':', $url, @rrest);
  my %lt=&Apache::lonlocal::texthash(   }
                 'up' => 'Move Up',  # Devalidate title cache
  'dw' => 'Move Down',   my $renamed_url=&LONCAPA::map::qtescape($url);
  'rm' => 'Remove',   &Apache::lonnet::devalidate_title_cache($renamed_url);
                 'ct' => 'Cut',      } else {
  'rn' => 'Rename',   return 0;
  'cp' => 'Copy');      }
         if ($env{'form.pagepath'}) {      return 1;
             $line.=(<<END);  }
 <form name="entry_$index" action="/adm/coursedocs" method="post">  
 <input type="hidden" name="pagepath" value="$env{'form.pagepath'}" />  sub editor {
 <input type="hidden" name="pagesymb" value="$env{'form.pagesymb'}" />      my ($r,$coursenum,$coursedom,$folder,$allowed,$upload_output,$type)=@_;
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />  
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      my $container= ($env{'form.pagepath'}) ? 'page'
 <input type="hidden" name="setparms" value="$orderidx" />                             : 'sequence';
 <td><table border='0' cellspacing='2' cellpadding='0'>  
 <tr><td bgcolor="#DDDDDD">      my ($errtext,$fatal) = &mapread($coursenum,$coursedom,
 <a href='/adm/coursedocs?cmd=up_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      $folder.'.'.$container);
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>      return $errtext if ($fatal);
 <tr><td bgcolor="#DDDDDD">  
 <a href='/adm/coursedocs?cmd=down_$index&pagepath=$pagepath&pagesymb=$pagesymb$cpinfo'>      if ($#LONCAPA::map::order<1) {
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>   my $idx=&LONCAPA::map::getresidx();
 </table></td>   if ($idx<=0) { $idx=1; }
 <td>$selectbox          $LONCAPA::map::order[0]=$idx;
 </td><td bgcolor="#DDDDDD">          $LONCAPA::map::resources[$idx]='';
 <a href='javascript:removeres("$pagepath","$index","$renametitle","page","$pagesymb");'>      }
 <font size="-2" color="#990000">$lt{'rm'}</font></a>     
 <a href='javascript:cutres("$pagepath","$index","$renametitle","page","$pagesymb");'>      my ($breadcrumbtrail,$randompick,$ishidden,$isencrypted,$plain,$is_random_order)=
 <font size="-2" color="#550044">$lt{'ct'}</font></a>   &breadcrumbs($folder,$allowed,$type);
 <a href='javascript:changename("$pagepath","$index","$renametitle","page","$pagesymb");'>      $r->print($breadcrumbtrail);
 <font size="-2" color="#009900">$lt{'rn'}</font></a>     
 <a href='javascript:markcopy("$pagepath","$index","$renametitle","page","$pagesymb");'>  # ------------------------------------------------------------ Process commands
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>  
 END  # ---------------- if they are for this folder and user allowed to make changes
         } else {      if (($allowed) && ($env{'form.folder'} eq $folder)) {
             $line.=(<<END);   # set parameters and change order
 <form name="entry_$index" action="/adm/coursedocs" method="post">   &snapshotbefore();
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  
 <input type="hidden" name="markedcopy_url" value="$env{'form.markedcopy_url'}" />   if (&update_parameter()) {
 <input type="hidden" name="markedcopy_title" value="$env{'form.markedcopy_title'}" />      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 <input type="hidden" name="setparms" value="$orderidx" />      return $errtext if ($fatal);
 <td><table border='0' cellspacing='2' cellpadding='0'>   }
 <tr><td bgcolor="#DDDDDD">  
 <a href='/adm/coursedocs?cmd=up_$index&folderpath=$folderpath$cpinfo'>   if ($env{'form.newpos'} && $env{'form.currentpos'}) {
 <img src="${iconpath}move_up.gif" alt='$lt{'up'}' border='0' /></a></td></tr>  # change order
 <tr><td bgcolor="#DDDDDD">      my $res = splice(@LONCAPA::map::order,$env{'form.currentpos'}-1,1);
 <a href='/adm/coursedocs?cmd=down_$index&folderpath=$folderpath$cpinfo'>      splice(@LONCAPA::map::order,$env{'form.newpos'}-1,0,$res);
 <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' border='0' /></a></td></tr>  
 </table></td>      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
 <td>$selectbox      return $errtext if ($fatal);
 </td><td bgcolor="#DDDDDD">   }
 <a href='javascript:removeres("$folderpath","$index","$renametitle","sequence");'>      
 <font size="-2" color="#990000">$lt{'rm'}</font></a>   if ($env{'form.pastemarked'}) {
 <a href='javascript:cutres("$folderpath","$index","$renametitle","sequence");'>              my $paste_res =
 <font size="-2" color="#550044">$lt{'ct'}</font></a>                  &do_paste_from_buffer($coursenum,$coursedom,$folder);
 <a href='javascript:changename("$folderpath","$index","$renametitle","sequence");'>              if ($paste_res eq 'ok') {
 <font size="-2" color="#009900">$lt{'rn'}</font></a>                  ($errtext,$fatal) = &storemap($coursenum,$coursedom,$folder.'.'.$container);
 <a href='javascript:markcopy("$folderpath","$index","$renametitle","sequence");'>                  return $errtext if ($fatal);
 <font size="-2" color="#000099">$lt{'cp'}</font></a></td>              } elsif ($paste_res ne '') {
 END                  $r->print('<p><span class="LC_error">'.$paste_res.'</span></p>');
         }              }
     }   }
 # Figure out what kind of a resource this is  
     my ($extension)=($url=~/\.(\w+)$/);   $r->print($upload_output);
     my $uploaded=($url=~/^\/*uploaded\//);  
     my $icon=&Apache::loncommon::icon($url);   if (&handle_edit_cmd()) {
     my $isfolder=0;      ($errtext,$fatal)=&storemap($coursenum,$coursedom,$folder.'.'.$container);
     my $ispage=0;      return $errtext if ($fatal);
     my $folderarg;   }
     my $pagearg;  # Group import/search
     my $pagefile;   if ($env{'form.importdetail'}) {
     if ($uploaded) {      my @imports;
  if ($extension eq 'sequence') {      foreach my $item (split(/\&/,$env{'form.importdetail'})) {
     $icon=$iconpath.'/folder_closed.gif';   if (defined($item)) {
     $url=~/$coursenum\/([\/\w]+)\.sequence$/;      my ($name,$url,$residx)=
     $url='/adm/coursedocs?';   map {&unescape($_)} split(/\=/,$item);
     $folderarg=$1;      push(@imports, [$name, $url, $residx]);
     $isfolder=1;   }
         } elsif ($extension eq 'page') {      }
             $icon=$iconpath.'/page.gif';      ($errtext,$fatal)=&group_import($coursenum, $coursedom, $folder,
             $url=~/$coursenum\/([\/\w]+)\.page$/;      $container,'londocs',@imports);
             $pagearg=$1;      return $errtext if ($fatal);
             $url='/adm/coursedocs?';   }
             $ispage=1;  # Loading a complete map
  } else {   if ($env{'form.loadmap'}) {
     &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);      if ($env{'form.importmap'}=~/\w/) {
  }   foreach my $res (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$env{'form.importmap'}))) {
     }      my ($title,$url,$ext,$type)=split(/\:/,$res);
     $url=~s/^http\&colon\;\/\//\/adm\/wrapper\/ext\//;      my $idx=&LONCAPA::map::getresidx($url);
     if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {      $LONCAPA::map::resources[$idx]=$res;
  my $symb=&Apache::lonnet::symbclean(      $LONCAPA::map::order[$#LONCAPA::map::order+1]=$idx;
           &Apache::lonnet::declutter('uploaded/'.   }
            $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.   ($errtext,$fatal)=&storemap($coursenum,$coursedom,
            $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.      $folder.'.'.$container);
            '.sequence').   return $errtext if ($fatal);
            '___'.$residx.'___'.      } else {
    &Apache::lonnet::declutter($url));   $r->print('<p><span class="LC_error">'.&mt('No map selected.').'</span></p>');
  (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);  
  $url=&Apache::lonnet::clutter($url);      }
  if ($url=~/^\/*uploaded\//) {   }
     $url=~/\.(\w+)$/;   &log_differences($plain);
     my $embstyle=&Apache::loncommon::fileembstyle($1);      }
     if (($embstyle eq 'img') || ($embstyle eq 'emb')) {  # ---------------------------------------------------------------- End commands
  $url='/adm/wrapper'.$url;  # ---------------------------------------------------------------- Print screen
     } elsif ($embstyle eq 'ssi') {      my $idx=0;
  #do nothing with these      my $shown=0;
     } elsif ($url!~/\.(sequence|page)$/) {      if (($ishidden) || ($isencrypted) || ($randompick>=0) || ($is_random_order)) {
  $url='/adm/coursedocs/showdoc'.$url;   $r->print('<p>'.&mt('Parameters').':<ul>'.
     }    ($randompick>=0?'<li>'.&mt('randomly pick [_1] resources',$randompick).'</li>':'').
  } elsif ($url=~m|^/ext/|) {     ($ishidden?'<li>'.&mt('contents hidden').'</li>':'').
     $url='/adm/wrapper'.$url;    ($isencrypted?'<li>'.&mt('URLs hidden').'</li>':'').
  }    '</ul></p>');
  $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);      }                                                                                                    
  if ($container eq 'page') {      if ($randompick>=0) {
     my $symb=$env{'form.pagesymb'};   $r->print('<p>'.&mt('Caution: this folder is set to randomly pick a subset of resources. Adding or removing resources from this folder will change the set of resources that the students see, resulting in spurious or missing credit for completed problems, not limited to ones you modify. Do not modify the contents of this folder if it is in active student use.').'</p>');
               }
     $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);      if ($is_random_order) {
     $url.=(($url=~/\?/)?'&':'?').'symb='.&Apache::lonnet::escape($symb);   $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>');
  }      }
     }      $r->print('<table class="LC_docs_editor">');
     my $parameterset='&nbsp;';      foreach my $res (@LONCAPA::map::order) {
     if ($isfolder) {   my ($name,$url)=split(/\:/,$LONCAPA::map::resources[$res]);
  my $foldername=&Apache::lonnet::escape($foldertitle);   $name=&LONCAPA::map::qtescape($name);
  my $folderpath=$env{'form.folderpath'};   $url=&LONCAPA::map::qtescape($url);
  if ($folderpath) { $folderpath.='&' };   unless ($name) {  $name=(split(/\//,$url))[-1]; }
  $folderpath.=$folderarg.'&'.$foldername;   unless ($name) { $idx++; next; }
  $url.='folderpath='.&Apache::lonnet::escape($folderpath).$cpinfo;   $r->print(&entryline($idx,$name,$url,$folder,$allowed,$res,
  $parameterset='<label>'.&mt('Randomly Pick: ').       $coursenum));
     '<input type="text" size="4" onChange="this.form.submit()" name="randpick_'.$orderidx.'" value="'.   $idx++;
     (&Apache::lonratedt::getparameter($orderidx,   $shown++;
                                               'parameter_randompick'))[0].      }
                                               '" />'.      unless ($shown) {
 '<font size="-2"><a href="javascript:void(0)">'.&mt('Store').'</a></font></label>';   $r->print('<tr><td>'.&mt('Currently no documents.').'</td></tr>');
              }
     }      $r->print("\n</table>\n");
     if ($ispage) {      if ($allowed) {
         my $pagename=&Apache::lonnet::escape($pagetitle);          &print_paste_buffer($r,$container);
         my $pagepath;      }
         my $folderpath=$env{'form.folderpath'};      return;
         if ($folderpath) { $pagepath = $folderpath.'&' };  }
         $pagepath.=$pagearg.'&'.$pagename;  
  my $symb=$env{'form.pagesymb'};  sub process_file_upload {
  if (!$symb) {      my ($upload_output,$coursenum,$coursedom,$allfiles,$codebase,$uploadcmd) = @_;
     my $path='uploaded/'.  # upload a file, if present
  $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.      my $parseaction;
  $env{'course.'.$env{'request.course.id'}.'.num'}.'/';     if ($env{'form.parserflag'}) {
     $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',          $parseaction = 'parse';
        $residx,      }
        $path.$pagearg.'.page');      my $phase_status;
  }      my $folder=$env{'form.folder'};
  $url.='pagepath='.&Apache::lonnet::escape($pagepath).      if ($folder eq '') {
     '&pagesymb='.&Apache::lonnet::escape($symb).$cpinfo;          $folder='default';
     }      }
     $line.='<td bgcolor="#FFFFBB"><a href="'.$url.'"><img src="'.$icon.      if ( ($folder=~/^$uploadcmd/) || ($uploadcmd eq 'default') ) {
  '" border="0"></a></td>'.          my $errtext='';
         "<td bgcolor='#FFFFBB'><a href='$url'>$title</a></td>";          my $fatal=0;
     if (($allowed) && ($folder!~/^supplemental/)) {          my $container='sequence';
   my %lt=&Apache::lonlocal::texthash(          if ($env{'form.pagepath'}) {
        'hd' => 'Hidden',              $container='page';
        'ec' => 'URL hidden');          }
  my $enctext=          ($errtext,$fatal)=
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');                &mapread($coursenum,$coursedom,$folder.'.'.$container);
  my $hidtext=          if ($#LONCAPA::map::order<1) {
     ((&Apache::lonratedt::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');              $LONCAPA::map::order[0]=1;
  $line.=(<<ENDPARMS);              $LONCAPA::map::resources[1]='';
 <td bgcolor="#BBBBFF"><font size='-2'>          }
 <nobr><label><input type="checkbox" name="hidprs_$orderidx" onClick="this.form.submit()" $hidtext /> $lt{'hd'}</label></nobr></td>          if ($fatal) {
 <td bgcolor="#BBBBFF"><font size='-2'>              return 'failed';
 <nobr><label><input type="checkbox" name="encprs_$orderidx" onClick="this.form.submit()" $enctext /> $lt{'ec'}</label></nobr></td>          }
 <td bgcolor="#BBBBFF"><font size="-2">$parameterset</font></td>          my $destination = 'docs/';
 ENDPARMS          if ($folder =~ /^supplemental/) {
     }              $destination = 'supplemental/';
     $line.="</form></tr>";          }
     return $line;          if (($folder eq 'default') || ($folder eq 'supplemental')) {
 }              $destination .= 'default/';
           } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
 # ---------------------------------------------------------------- tie the hash              $destination .=  $2.'/';
           }
 sub tiehash {  # this is for a course, not a user, so set coursedoc flag
     my ($mode)=@_;  # probably the only place in the system where this should be "1"
     $hashtied=0;          my $newidx=&LONCAPA::map::getresidx();
     if ($env{'request.course.fn'}) {          $destination .= $newidx;
  if ($mode eq 'write') {          my $url=&Apache::lonnet::userfileupload('uploaddoc',1,$destination,
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",   $parseaction,$allfiles,
     &GDBM_WRCREAT(),0640)) {   $codebase);
                 $hashtied=2;          my $ext='false';
     }          if ($url=~m{^http://}) { $ext='true'; }
  } else {   $url     = &LONCAPA::map::qtunescape($url);
     if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",          my $comment=$env{'form.comment'};
     &GDBM_READER(),0640)) {   $comment = &LONCAPA::map::qtunescape($comment);
                 $hashtied=1;          if ($folder=~/^supplemental/) {
     }                $comment=time.'___&&&___'.$env{'user.name'}.'___&&&___'.
  }                    $env{'user.domain'}.'___&&&___'.$comment;
     }              }
 }  
           $LONCAPA::map::resources[$newidx]=
 sub untiehash {      $comment.':'.$url.':'.$ext.':normal:res';
     if ($hashtied) { untie %hash; }          $LONCAPA::map::order[$#LONCAPA::map::order+1]= $newidx;
     $hashtied=0;          ($errtext,$fatal)=&storemap($coursenum,$coursedom,
 }      $folder.'.'.$container);
           if ($fatal) {
 # --------------------------------------------------------------- check on this              $$upload_output .= '<p><span class="LC_error">'.$errtext.'</span></p>';
               return 'failed';
 sub checkonthis {          } else {
     my ($r,$url,$level,$title)=@_;              if ($parseaction eq 'parse') {
     $url=&Apache::lonnet::unescape($url);                  my $total_embedded = keys(%{$allfiles});
     $alreadyseen{$url}=1;                  if ($total_embedded > 0) {
     $r->rflush();                      my $num = 0;
     if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {      my $state = '
        $r->print("\n<br />");     <input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($env{'form.folderpath'},'<>&"').'" />
        for (my $i=0;$i<=$level*5;$i++) {     <input type="hidden" name="cmd" value="upload_embedded" />
            $r->print('&nbsp;');     <input type="hidden" name="newidx" value="'.$newidx.'" />
        }     <input type="hidden" name="primaryurl" value="'.&escape($url).'" />
        $r->print('<a href="'.$url.'" target="cat">'.     <input type="hidden" name="phasetwo" value="'.$total_embedded.'" />';
  ($title?$title:$url).'</a> ');      $phase_status = 'phasetwo';
        if ($url=~/^\/res\//) {  
   my $result=&Apache::lonnet::repcopy(                      $$upload_output .=
                               &Apache::lonnet::filelocation('',$url));   'This file contains embedded multimedia objects, which need to be uploaded to LON-CAPA.<br />'.
           if ($result eq 'ok') {   &Apache::loncommon::ask_for_embedded_content(
              $r->print('<font color="green">'.&mt('ok').'</font>');                              '/adm/coursedocs',$state,$allfiles,$codebase);
              $r->rflush();                  } else {
              &Apache::lonnet::countacc($url);                      $$upload_output .= 'No embedded items identified<br />';
              $url=~/\.(\w+)$/;                  }
              if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {              }
  $r->print('<br />');          }
                  $r->rflush();      }
                  for (my $i=0;$i<=$level*5;$i++) {      return $phase_status;
                      $r->print('&nbsp;');  }
                  }  
                  $r->print('- '.&mt('Rendering').': ');  sub process_secondary_uploads {
  my ($errorcount,$warningcount)=split(/:/,      my ($upload_output,$coursedom,$coursenum,$formname,$num,$newidx) = @_;
        &Apache::lonnet::ssi_body($url,      my $folder=$env{'form.folder'};
        ('grade_target'=>'web',      my $destination = 'docs/';
  'return_only_error_and_warning_counts' => 1)));      if ($folder =~ /^supplemental/) {
                  if (($errorcount) ||          $destination = 'supplemental/';
                      ($warningcount)) {      }
      if ($errorcount) {      if (($folder eq 'default') || ($folder eq 'supplemental')) {
                         $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.          $destination .= 'default/';
   $errorcount.' '.      } elsif ($folder =~ /^(default|supplemental)_(\d+)$/) {
   &mt('error(s)').'</b></font> ');          $destination .=  $2.'/';
                      }      }
      if ($warningcount) {      $destination .= $newidx;
                         $r->print('<font color="blue">'.      my ($url,$filename);
   $warningcount.' '.      $url=&Apache::lonnet::userfileupload($formname.$num,1,$destination);
   &mt('warning(s)').'</font>');      ($filename) = ($url =~ m{^/uploaded/\Q$coursedom\E/\Q$coursenum\E/\Q$destination\E/(.+)$});
                      }      return $filename;
                  } else {  }
                      $r->print('<font color="green">'.&mt('ok').'</font>');  
                  }  sub is_supplemental_title {
                  $r->rflush();      my ($title) = @_;
              }      return scalar($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/);
      my $dependencies=  }
                 &Apache::lonnet::metadata($url,'dependencies');  
              foreach (split(/\,/,$dependencies)) {  sub parse_supplemental_title {
  if (($_=~/^\/res\//) && (!$alreadyseen{$_})) {      my ($title) = @_;
                     &checkonthis($r,$_,$level+1);  
                  }      my ($foldertitle,$renametitle);
              }      if ($title =~ /&amp;&amp;&amp;/) {
           } elsif ($result eq 'unavailable') {   $title = &HTML::Entites::decode($title);
              $r->print('<font color="red"><b>'.&mt('connection down').'</b></font>');      }
           } elsif ($result eq 'not_found') {   if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
       unless ($url=~/\$/) {   $renametitle=$4;
   $r->print('<font color="red"><b>'.&mt('not found').'</b></font>');   my ($time,$uname,$udom) = ($1,$2,$3);
       } else {   $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
   $r->print('<font color="yellow"><b>'.&mt('unable to verify variable URL').'</b></font>');   my $name =  &Apache::loncommon::plainname($uname,$udom);
       }   $name = &HTML::Entities::encode($name,'"<>&\'');
           } else {   $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
              $r->print('<font color="red"><b>'.&mt('access denied').'</b></font>');      $name.': <br />'.$foldertitle;
           }      }
       }      if (wantarray) {
    }   return ($title,$foldertitle,$renametitle);
 }      }
       return $title;
   }
 #  
 # -------------------------------------------------------------- Verify Content  # --------------------------------------------------------------- An entry line
 #   
 sub verifycontent {  sub entryline {
    my $r=shift;       my ($index,$title,$url,$folder,$allowed,$residx,$coursenum)=@_;
    my $loaderror=&Apache::lonnet::overloaderror($r);  
    if ($loaderror) { return $loaderror; }      my ($foldertitle,$pagetitle,$renametitle);
    my $html=&Apache::lonxml::xmlbegin();      if (&is_supplemental_title($title)) {
    $r->print($html.'<head><title>Verify Content</title></head>'.   ($title,$foldertitle,$renametitle) = &parse_supplemental_title($title);
               &Apache::loncommon::bodytag('Verify Course Documents'));   $pagetitle = $foldertitle;
    $hashtied=0;      } else {
    undef %alreadyseen;   $title=&HTML::Entities::encode($title,'"<>&\'');
    %alreadyseen=();   $renametitle=$title;
    &tiehash();   $foldertitle=$title;
    foreach (keys %hash) {   $pagetitle=$title;
        if ($hash{$_}=~/\.(page|sequence)$/) {      }
    if (($_=~/^src_/) && ($alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {  
        $r->print('<hr /><font color="red">'.      my $orderidx=$LONCAPA::map::order[$index];
  &mt('The following sequence or page is included more than once in your course: ').     
  &Apache::lonnet::unescape($hash{$_}).'</font><br />'.  
  &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));      $renametitle=~s/\\/\\\\/g;
    }      $renametitle=~s/\&quot\;/\\\"/g;
        }      $renametitle=~s/ /%20/g;
        if (($_=~/^src\_(.+)$/) && (!$alreadyseen{&Apache::lonnet::unescape($hash{$_})})) {      my $line='<tr>';
            &checkonthis($r,$hash{$_},0,$hash{'title_'.$1});      my ($form_start,$form_end);
        }  # Edit commands
    }      my ($container, $type, $esc_path, $path, $symb);
    &untiehash();      if ($env{'form.folderpath'}) {
    $r->print('<h1>'.&mt('Done').'.</h1>'.'<a href="/adm/coursedocs">'.   $type = 'folder';
      &mt('Return to DOCS').'</a>');          $container = 'sequence';
 }   $esc_path=&escape($env{'form.folderpath'});
    $path = &HTML::Entities::encode($env{'form.folderpath'},'<>&"');
    # $htmlfoldername=&HTML::Entities::encode($env{'form.foldername'},'<>&"');
 # -------------------------------------------------------------- Check Versions      }
       if ($env{'form.pagepath'}) {
 sub devalidateversioncache {          $type = $container = 'page';
     my $src=shift;          $esc_path=&escape($path = $env{'form.pagepath'});
     &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.   $path = &HTML::Entities::encode($env{'form.pagepath'},'<>&"');
   &Apache::lonnet::clutter($src));          $symb=&escape($env{'form.pagesymb'});
 }      }
       my $cpinfo='';
 sub checkversions {      if ($allowed) {
     my $r=shift;   my $incindex=$index+1;
     my $html=&Apache::lonxml::xmlbegin();   my $selectbox='';
     $r->print($html.'<head><title>Check Versions</title></head>'.   if (($folder!~/^supplemental/) &&
               &Apache::loncommon::bodytag('Check Course Document Versions'));      ($#LONCAPA::map::order>0) &&
     my $header='';      ((split(/\:/,
     my $startsel='';       $LONCAPA::map::resources[$LONCAPA::map::order[0]]))[1]
     my $monthsel='';       ne '') &&
     my $weeksel='';      ((split(/\:/,
     my $daysel='';       $LONCAPA::map::resources[$LONCAPA::map::order[1]]))[1]
     my $allsel='';       ne '')) {
     my %changes=();      $selectbox=
     my $starttime=0;   '<input type="hidden" name="currentpos" value="'.$incindex.'" />'.
     my $haschanged=0;   '<select name="newpos" onChange="this.form.submit()">';
     my %setversions=&Apache::lonnet::dump('resourceversions',      for (my $i=1;$i<=$#LONCAPA::map::order+1;$i++) {
   $env{'course.'.$env{'request.course.id'}.'.domain'},   if ($i==$incindex) {
   $env{'course.'.$env{'request.course.id'}.'.num'});      $selectbox.='<option value="" selected="1">('.$i.')</option>';
    } else {
     $hashtied=0;      $selectbox.='<option value="'.$i.'">'.$i.'</option>';
     &tiehash();   }
     my %newsetversions=();      }
     if ($env{'form.setmostrecent'}) {      $selectbox.='</select>';
  $haschanged=1;   }
  foreach (keys %hash) {   my %lt=&Apache::lonlocal::texthash(
     if ($_=~/^ids\_(\/res\/.+)$/) {                  'up' => 'Move Up',
  $newsetversions{$1}='mostrecent';   'dw' => 'Move Down',
                 &devalidateversioncache($1);   'rm' => 'Remove',
     }                  'ct' => 'Cut',
  }   'rn' => 'Rename',
     } elsif ($env{'form.setcurrent'}) {   'cp' => 'Copy');
  $haschanged=1;   my $nocopy=0;
  foreach (keys %hash) {          my $nocut=0;
     if ($_=~/^ids\_(\/res\/.+)$/) {          if ($url=~/\.(page|sequence)$/) {
  my $getvers=&Apache::lonnet::getversion($1);      if ($url =~ m{/res/}) {
  if ($getvers>0) {   # no copy for published maps
     $newsetversions{$1}=$getvers;   $nocopy = 1;
     &devalidateversioncache($1);      } else {
  }   foreach my $item (&Apache::lonsequence::attemptread(&Apache::lonnet::filelocation('',$url),1)) {
     }      my ($title,$url,$ext,$type)=split(/\:/,$item);
  }      if (($url=~/\.(page|sequence)/) && ($type ne 'zombie')) {
     } elsif ($env{'form.setversions'}) {   $nocopy=1;
  $haschanged=1;   last;
  foreach (keys %env) {      }
     if ($_=~/^form\.set_version_(.+)$/) {   }
  my $src=$1;      }
  if (($env{$_}) && ($env{$_} ne $setversions{$src})) {   }
     $newsetversions{$src}=$env{$_};          if ($url=~/^\/res\/lib\/templates\//) {
     &devalidateversioncache($src);             $nocopy=1;
  }             $nocut=1;
     }          }
  }          my $copylink='&nbsp;';
     }          my $cutlink='&nbsp;';
     if ($haschanged) {  
         if (&Apache::lonnet::put('resourceversions',\%newsetversions,   my $skip_confirm = 0;
   $env{'course.'.$env{'request.course.id'}.'.domain'},   if ( $folder =~ /^supplemental/
   $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {       || ($url =~ m{( /smppg$
     $r->print('<h1>'.&mt('Your Version Settings have been Stored').'</h1>');      |/syllabus$
  } else {      |/aboutme$
     $r->print('<h1><font color="red">'.&mt('An Error Occured while Attempting to Store your Version Settings').'</font></h1>');      |/navmaps$
  }      |/bulletinboard$
  &mark_hash_old();      |\.html$
     }      |^/adm/wrapper/ext)}x)) {
     &changewarning($r,'');      $skip_confirm = 1;
     if ($env{'form.timerange'} eq 'all') {   }
 # show all documents  
  $header=&mt('All Documents in Course');   if (!$nocopy) {
  $allsel=1;      $copylink=(<<ENDCOPY);
  foreach (keys %hash) {  <a href='javascript:markcopy("$esc_path","$index","$renametitle","$container","$symb","$folder");' class="LC_docs_copy">$lt{'cp'}</a>
     if ($_=~/^ids\_(\/res\/.+)$/) {  ENDCOPY
  my $src=$1;          }
  $changes{$src}=1;   if (!$nocut) {
     }      $cutlink=(<<ENDCUT);
  }  <a href='javascript:cutres("$esc_path","$index","$renametitle","$container","$symb","$folder",$skip_confirm);' class="LC_docs_cut">$lt{'ct'}</a>
     } else {  ENDCUT
 # show documents which changed          }
  %changes=&Apache::lonnet::dump   $form_start = (<<END);
  ('versionupdate',$env{'course.'.$env{'request.course.id'}.'.domain'},     <form  action="/adm/coursedocs" method="post">
                      $env{'course.'.$env{'request.course.id'}.'.num'});     <input type="hidden" name="${type}path" value="$path" />
  my $firstkey=(keys %changes)[0];     <input type="hidden" name="${type}symb" value="$symb" />
  unless ($firstkey=~/^error\:/) {     <input type="hidden" name="setparms" value="$orderidx" />
     unless ($env{'form.timerange'}) {     <input type="hidden" name="changeparms" value="0" />
  $env{'form.timerange'}=604800;  END
     }          $form_end = '</form>';
     my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '   $line.=(<<END);
  .&mt('seconds');  <td>
     if ($env{'form.timerange'}==-1) {     <table class="LC_docs_entry_move">
  $seltext='since start of course';        <tr>
  $startsel='selected';           <td>
  $env{'form.timerange'}=time;              <a href='/adm/coursedocs?cmd=up_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" /></a>
     }           </td>
     $starttime=time-$env{'form.timerange'};        </tr>
     if ($env{'form.timerange'}==2592000) {        <tr>
  $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';          <td>
  $monthsel='selected';             <a href='/adm/coursedocs?cmd=down_$index&amp;${type}path=$esc_path&amp;${type}symb=$symb$cpinfo'><img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" /></a>
     } elsif ($env{'form.timerange'}==604800) {          </td>
  $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';        </tr>
  $weeksel='selected';      </table>
     } elsif ($env{'form.timerange'}==86400) {  </td>
  $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';  <td>
  $daysel='selected';     $form_start
     }     $selectbox
     $header=&mt('Content changed').' '.$seltext;     $form_end
  } else {  </td>
     $header=&mt('No content modifications yet.');  <td class="LC_docs_entry_commands">
  }     <a href='javascript:removeres("$esc_path","$index","$renametitle","$container","$symb",$skip_confirm);' class="LC_docs_remove">$lt{'rm'}</a>
     }  $cutlink
     %setversions=&Apache::lonnet::dump('resourceversions',     <a href='javascript:changename("$esc_path","$index","$renametitle","$container","$symb");' class="LC_docs_rename">$lt{'rn'}</a>
   $env{'course.'.$env{'request.course.id'}.'.domain'},  $copylink
   $env{'course.'.$env{'request.course.id'}.'.num'});  </td>
     my %lt=&Apache::lonlocal::texthash  END
       ('st' => 'Version changes since start of Course',  
        'lm' => 'Version changes since last Month',      }
        'lw' => 'Version changes since last Week',  # Figure out what kind of a resource this is
        'sy' => 'Version changes since Yesterday',      my ($extension)=($url=~/\.(\w+)$/);
                'al' => 'All Resources (possibly large output)',      my $uploaded=($url=~/^\/*uploaded\//);
        'sd' => 'Display',      my $icon=&Apache::loncommon::icon($url);
        'fi' => 'File',      my $isfolder=0;
        'md' => 'Modification Date',      my $ispage=0;
                'mr' => 'Most recently published Version',      my $folderarg;
        've' => 'Version used in Course',      my $pagearg;
                'vu' => 'Set Version to be used in Course',      my $pagefile;
 'sv' => 'Set Versions to be used in Course according to Selections below',      if ($uploaded) {
 'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',   if ($extension eq 'sequence') {
 'sc' => 'Set all Resource Versions to current Version (Fix Versions)',      $icon=$iconpath.'/folder_closed.gif';
        'di' => 'Differences');      $url=~/\Q$coursenum\E\/([\/\w]+)\.sequence$/;
     $r->print(<<ENDHEADERS);      $url='/adm/coursedocs?';
 <form action="/adm/coursedocs" method="post">      $folderarg=$1;
 <input type="hidden" name="versions" value="1" />      $isfolder=1;
 <input type="submit" name="setmostrecent" value="$lt{'sm'}" />          } elsif ($extension eq 'page') {
 <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />              $icon=$iconpath.'/page.gif';
 <select name="timerange">              $url=~/\Q$coursenum\E\/([\/\w]+)\.page$/;
 <option value='all' $allsel>$lt{'al'}</option>              $pagearg=$1;
 <option value="-1" $startsel>$lt{'st'}</option>              $url='/adm/coursedocs?';
 <option value="2592000" $monthsel>$lt{'lm'}</option>              $ispage=1;
 <option value="604800" $weeksel>$lt{'lw'}</option>   } else {
 <option value="86400" $daysel>$lt{'sy'}</option>      &Apache::lonnet::allowuploaded('/adm/coursedoc',$url);
 </select>   }
 <input type="submit" name="display" value="$lt{'sd'}" />      }
 <h3>$header</h3>     
 <input type="submit" name="setversions" value="$lt{'sv'}" />      my $orig_url = $url;
 <table border="0">      my $external = ($url=~s{^http(|s)(&colon;|:)//}{/adm/wrapper/ext/});
 ENDHEADERS      if ((!$isfolder) && ($residx) && ($folder!~/supplemental/) && (!$ispage)) {
     foreach (sort keys %changes) {   my $symb=&Apache::lonnet::symbclean(
  if ($changes{$_}>$starttime) {            &Apache::lonnet::declutter('uploaded/'.
     my ($root,$extension)=($_=~/^(.*)\.(\w+)$/);             $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
     my $currentversion=&Apache::lonnet::getversion($_);             $env{'course.'.$env{'request.course.id'}.'.num'}.'/'.$folder.
     if ($currentversion<0) {             '.sequence').
  $currentversion=&mt('Could not be determined.');             '___'.$residx.'___'.
     }     &Apache::lonnet::declutter($url));
     my $linkurl=&Apache::lonnet::clutter($_);   (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
     $r->print(   $url=&Apache::lonnet::clutter($url);
       '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.   if ($url=~/^\/*uploaded\//) {
       &Apache::lonnet::gettitle($linkurl).      $url=~/\.(\w+)$/;
                       '</b></font></td></tr>'.      my $embstyle=&Apache::loncommon::fileembstyle($1);
                       '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.      if (($embstyle eq 'img') || ($embstyle eq 'emb')) {
                       '<td colspan="4">'.   $url='/adm/wrapper'.$url;
                       '<a href="'.$linkurl.'" target="cat">'.$linkurl.      } elsif ($embstyle eq 'ssi') {
       '</a></td></tr>'.   #do nothing with these
                       '<tr><td></td>'.      } elsif ($url!~/\.(sequence|page)$/) {
                       '<td title="'.$lt{'md'}.'">'.   $url='/adm/coursedocs/showdoc'.$url;
       &Apache::lonlocal::locallocaltime(      }
                            &Apache::lonnet::metadata($root.'.'.$extension,   } elsif ($url=~m|^/ext/|) {
                                                      'lastrevisiondate')      $url='/adm/wrapper'.$url;
                                                         ).      $external = 1;
                       '</td>'.   }
                       '<td title="'.$lt{'mr'}.'"><nobr>Most Recent: '.          if (&Apache::lonnet::symbverify($symb,$url)) {
                       '<font size="+1">'.$currentversion.'</font>'.      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
                       '</nobr></td>'.          } else {
                       '<td title="'.$lt{'ve'}.'"><nobr>In Course: '.              $url='';
                       '<font size="+1">');          }
 # Used in course   if ($container eq 'page') {
     my $usedversion=$hash{'version_'.$linkurl};      my $symb=$env{'form.pagesymb'};
     if (($usedversion) && ($usedversion ne 'mostrecent')) {          
  $r->print($usedversion);      $url=&Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
     } else {      $url.=(($url=~/\?/)?'&':'?').'symb='.&escape($symb);
  $r->print($currentversion);   }
     }      }
     $r->print('</font></nobr></td><td title="'.$lt{'vu'}.'">'.      my ($parameterset,$rand_order_text) = ('&nbsp;', '&nbsp;');
                       '<nobr>Use: ');      if ($isfolder || $extension eq 'sequence') {
 # Set version   my $foldername=&escape($foldertitle);
     $r->print(&Apache::loncommon::select_form($setversions{$linkurl},   my $folderpath=$env{'form.folderpath'};
       'set_version_'.$linkurl,   if ($folderpath) { $folderpath.='&' };
       ('select_form_order' =>  # Append randompick number, hidden, and encrypted with ":" to foldername,
        ['',1..$currentversion,'mostrecent'],  # so it gets transferred between levels
        '' => '',   $folderpath.=$folderarg.'&'.$foldername.':'.(&LONCAPA::map::getparameter($orderidx,
        'mostrecent' => 'most recent',                                                'parameter_randompick'))[0]
        map {$_,$_} (1..$currentversion))));                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     $r->print('</nobr></td></tr><tr><td></td>');                                                'parameter_hiddenresource'))[0]=~/^yes$/i)
     my $lastold=1;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
     for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {                                                'parameter_encrypturl'))[0]=~/^yes$/i)
  my $url=$root.'.'.$prevvers.'.'.$extension;                                                 .':'.((&LONCAPA::map::getparameter($orderidx,
  if (&Apache::lonnet::metadata($url,'lastrevisiondate')<                                                'parameter_randomorder'))[0]=~/^yes$/i);
     $starttime) {   $url.='folderpath='.&escape($folderpath).$cpinfo;
     $lastold=$prevvers;   $parameterset='<label>'.&mt('Randomly Pick: ').
  }      '<input type="text" size="4" onChange="this.form.changeparms.value='."'randompick'".';this.form.submit()" name="randompick_'.$orderidx.'" value="'.
     }      (&LONCAPA::map::getparameter($orderidx,
             #                                                 'parameter_randompick'))[0].
             # Code to figure out how many version entries should go in                                                '" />'.
             # each of the four columns  '<a href="javascript:void(0)">'.&mt('Save').'</a></label>';
             my $entries_per_col = 0;      my $ro_set=
             my $num_entries = ($currentversion-$lastold);      ((&LONCAPA::map::getparameter($orderidx,'parameter_randomorder'))[0]=~/^yes$/i?' checked="checked"':'');
             if ($num_entries % 4 == 0) {   $rand_order_text ='
                 $entries_per_col = $num_entries/4;  <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>';  
             } else {      }
                 $entries_per_col = $num_entries/4 + 1;      if ($ispage) {
             }          my $pagename=&escape($pagetitle);
             my $entries_count = 0;          my $pagepath;
             $r->print('<td valign="top"><font size="-2">');           my $folderpath=$env{'form.folderpath'};
             my $cols_output = 1;          if ($folderpath) { $pagepath = $folderpath.'&' };
             for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {          $pagepath.=$pagearg.'&'.$pagename;
  my $url=$root.'.'.$prevvers.'.'.$extension;   my $symb=$env{'form.pagesymb'};
  $r->print('<nobr><a href="'.&Apache::lonnet::clutter($url).   if (!$symb) {
   '">'.&mt('Version').' '.$prevvers.'</a> ('.      my $path='uploaded/'.
   &Apache::lonlocal::locallocaltime(   $env{'course.'.$env{'request.course.id'}.'.domain'}.'/'.
                                 &Apache::lonnet::metadata($url,   $env{'course.'.$env{'request.course.id'}.'.num'}.'/';
                                                           'lastrevisiondate')      $symb=&Apache::lonnet::encode_symb($path.$folder.'.sequence',
                                                             ).         $residx,
   ')');         $path.$pagearg.'.page');
  if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {   }
                     $r->print(' <a href="/adm/diff?filename='.   $url.='pagepath='.&escape($pagepath).
       &Apache::lonnet::clutter($root.'.'.$extension).      '&amp;pagesymb='.&escape($symb).$cpinfo;
       '&versionone='.$prevvers.      }
       '">'.&mt('Diffs').'</a>');      if ($external) {
  }   my $form = ($folder =~ /^default/)? 'newext' : 'supnewext';
  $r->print('</nobr><br />');   $external = '&nbsp;<a class="LC_docs_ext_edit" href="javascript:edittext(\''.$form.'\',\''.$residx.'\',\''.&escape($title).'\',\''.&escape($orig_url).'\');" >'.&mt('Edit').'</a>';
                 if (++$entries_count % $entries_per_col == 0) {      } else {
                     $r->print('</font></td>');   undef($external);
                     if ($cols_output != 4) {      }
                         $r->print('<td valign="top"><font size="-2">');      $line.='
                         $cols_output++;    <td class="LC_docs_entry_icon">
                     }      '.($url?'<a href="'.$url.'">':'').'<img src="'.$icon.'" alt="" class="LC_icon" />'.($url?'</a>':'').'
                 }    </td>
     }    <td class="LC_docs_entry_title">
             while($cols_output++ < 4) {      '.($url?"<a href=\"$url\">":'').$title.($url?'</a>':' <span class="LC_docs_reinit_warn">'.&mt('(re-initialize course to access)').'</span>').$external."
                 $r->print('</font></td><td><font>')    </td>";
             }      if (($allowed) && ($folder!~/^supplemental/)) {
     $r->print('</font></td></tr>'."\n");    my %lt=&Apache::lonlocal::texthash(
  }         'hd' => 'Hidden',
     }         'ec' => 'URL hidden');
     $r->print('</table></form>');   my $enctext=
     $r->print('<h1>'.&mt('Done').'.</h1>');      ((&LONCAPA::map::getparameter($orderidx,'parameter_encrypturl'))[0]=~/^yes$/i?' checked="1"':'');
    my $hidtext=
     &untiehash();      ((&LONCAPA::map::getparameter($orderidx,'parameter_hiddenresource'))[0]=~/^yes$/i?' checked="1"':'');
 }   $line.=(<<ENDPARMS);
     <td class="LC_docs_entry_parameter">
 sub mark_hash_old {      $form_start
     my $retie_hash=0;      <label><input type="checkbox" name="hiddenresource_$orderidx" onClick="this.form.changeparms.value='hiddenresource';this.form.submit()" $hidtext /> $lt{'hd'}</label>
     if ($hashtied) {      $form_end
  $retie_hash=1;    </td>
  &untiehash();    <td class="LC_docs_entry_parameter">
     }      $form_start
     &tiehash('write');      <label><input type="checkbox" name="encrypturl_$orderidx" onClick="this.form.changeparms.value='encrypturl';this.form.submit()" $enctext /> $lt{'ec'}</label>
     $hash{'old'}=1;      $form_end
     &untiehash();    </td>
     if ($retie_hash) { &tiehash(); }    <td class="LC_docs_entry_parameter">$form_start $rand_order_text $form_end</td>
 }    <td class="LC_docs_entry_parameter">$form_start $parameterset $form_end</td>
   ENDPARMS
 sub is_hash_old {      }
     my $untie_hash=0;      $line.="</tr>";
     if (!$hashtied) {      return $line;
  $untie_hash=1;  }
  &tiehash();  
     }  =pod
     my $return=$hash{'old'};  
     if ($untie_hash) { &untiehash(); }  =item tiehash()
     return $return;  
 }  tie the hash
   
 sub changewarning {  =cut
     my ($r,$postexec,$message,$url)=@_;  
     if (!&is_hash_old()) { return; }  sub tiehash {
     my $pathvar='folderpath';      my ($mode)=@_;
     my $path=&Apache::lonnet::escape($env{'form.folderpath'});      $hashtied=0;
     if (!defined($url)) {      if ($env{'request.course.fn'}) {
  if (defined($env{'form.pagepath'})) {   if ($mode eq 'write') {
     $pathvar='pagepath';      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     $path=&Apache::lonnet::escape($env{'form.pagepath'});      &GDBM_WRCREAT(),0640)) {
     $path.='&amp;pagesymb='.&Apache::lonnet::escape($env{'form.pagesymb'});                  $hashtied=2;
  }      }
  $url='/adm/coursedocs?'.$pathvar.'='.$path;   } else {
     }      if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.".db",
     if (!defined($message)) {      &GDBM_READER(),0640)) {
  $message='Changes will become active for your current session after [_1], or the next time you log in.';                  $hashtied=1;
     }      }
     $r->print("\n\n".   }
 '<script>function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".       }    
 '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.  }
 '<input type="hidden" name="orgurl" value="'.$url.  
 '" /><input type="hidden" name="selectrole" value="1" /><h3><font color="red">'.  sub untiehash {
 &mt($message,' <input type="hidden" name="'.      if ($hashtied) { untie %hash; }
     $env{'request.role'}.'" value="1" /><input type="button" value="'.      $hashtied=0;
     &mt('re-initializing course').'" onClick="reinit(this.form)" />').      return OK;
 $help{'Caching'}.'</font></h3></form>'."\n\n");  }
 }  
   
 # ================================================================ Main Handler  
 sub handler {  
     my $r = shift;  sub checkonthis {
     &Apache::loncommon::content_type($r,'text/html');      my ($r,$url,$level,$title)=@_;
     $r->send_http_header;      $url=&unescape($url);
     return OK if $r->header_only;      $alreadyseen{$url}=1;
       $r->rflush();
 # --------------------------------------------- Initialize help topics for this      if (($url) && ($url!~/^\/uploaded\//) && ($url!~/\*$/)) {
   foreach ('Adding_Course_Doc','Main_Course_Documents',         $r->print("\n<br />");
            'Adding_External_Resource','Navigate_Content',         if ($level==0) {
            'Adding_Folders','Docs_Overview', 'Load_Map',             $r->print("<br />");
            'Supplemental','Score_Upload_Form','Adding_Pages',         }
            'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',         for (my $i=0;$i<=$level*5;$i++) {
    'Check_Resource_Versions','Verify_Content') {             $r->print('&nbsp;');
       $help{$_}=&Apache::loncommon::help_open_topic('Docs_'.$_);         }
   }         $r->print('<a href="'.$url.'" target="cat">'.
     # Composite help files   ($title?$title:$url).'</a> ');
     $help{'Syllabus'} = &Apache::loncommon::help_open_topic(         if ($url=~/^\/res\//) {
     'Docs_About_Syllabus,Docs_Editing_Templated_Pages');    my $result=&Apache::lonnet::repcopy(
     $help{'Simple Page'} = &Apache::loncommon::help_open_topic(                                &Apache::lonnet::filelocation('',$url));
     'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');            if ($result eq 'ok') {
     $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(               $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     'Option_Response_Simple');               $r->rflush();
     $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(               &Apache::lonnet::countacc($url);
     'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');               $url=~/\.(\w+)$/;
     $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(               if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
   'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');   $r->print('<br />');
     $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');                   $r->rflush();
                    for (my $i=0;$i<=$level*5;$i++) {
   if ($env{'form.verify'}) {                       $r->print('&nbsp;');
       &verifycontent($r);                   }
   } elsif ($env{'form.versions'}) {                   $r->print('- '.&mt('Rendering:').' ');
       &checkversions($r);   my ($errorcount,$warningcount)=split(/:/,
   } elsif ($env{'form.dumpcourse'}) {         &Apache::lonnet::ssi_body($url,
       &dumpcourse($r);         ('grade_target'=>'web',
   } elsif ($env{'form.exportcourse'}) {   'return_only_error_and_warning_counts' => 1)));
       &exportcourse($r);                   if (($errorcount) ||
   } else {                       ($warningcount)) {
 # is this a standard course?       if ($errorcount) {
                           $r->print('<img src="/adm/lonMisc/bomb.gif" /><span class="LC_error">'.
     my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);                            &mt('[quant,_1,error]',$errorcount).'</span>');
     my $forcestandard = 0;                       }
     my $forcesupplement;       if ($warningcount) {
     my $script='';                          $r->print('<span class="LC_warning">'.
     my $allowed;                            &mt('[quant,_1,warning]',$warningcount).'</span>');
     my $events='';                       }
     my $showdoc=0;                   } else {
     my $containertag;                       $r->print('<span class="LC_success">'.&mt('ok').'</span>');
     my $uploadtag;                   }
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},                   $r->rflush();
     ['folderpath','pagepath','pagesymb','markedcopy_url','markedcopy_title']);               }
     if ($env{'form.folderpath'}) {       my $dependencies=
  my (@folderpath)=split('&',$env{'form.folderpath'});                  &Apache::lonnet::metadata($url,'dependencies');
  $env{'form.foldername'}=&Apache::lonnet::unescape(pop(@folderpath));               foreach my $dep (split(/\,/,$dependencies)) {
  $env{'form.folder'}=pop(@folderpath);   if (($dep=~/^\/res\//) && (!$alreadyseen{$dep})) {
     }                      &checkonthis($r,$dep,$level+1);
     if ($env{'form.pagepath'}) {                   }
         my (@pagepath)=split('&',$env{'form.pagepath'});               }
         $env{'form.pagename'}=&Apache::lonnet::unescape(pop(@pagepath));            } elsif ($result eq 'unavailable') {
         $env{'form.folder'}=pop(@pagepath);               $r->print('<span class="LC_error">'.&mt('connection down').'</span>');
         $containertag = '<input type="hidden" name="pagepath" value="" />'.            } elsif ($result eq 'not_found') {
     '<input type="hidden" name="pagesymb" value="" />';        unless ($url=~/\$/) {
         $uploadtag = '<input type="hidden" name="pagepath" value="'.$env{'form.pagepath'}.'" />'.    $r->print('<span class="LC_error">'.&mt('not found').'</b></span>');
     '<input type="hidden" name="pagesymb" value="'.$env{'form.pagesymb'}.'" />';        } else {
     }    $r->print('<span class="LC_unknown">'.&mt('unable to verify variable URL').'</span>');
     if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {        }
        $showdoc='/'.$1;            } else {
     }               $r->print('<span class="LC_error">'.&mt('access denied').'</span>');
     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_/);  
   
 # does this user have privileges to post, etc?  =pod
        $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});  
        if ($allowed) {   =item list_symbs()
          &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);  
          $script=&Apache::lonratedt::editscript('simple');   List Symbs
        }  
     } else { # got called in sequence from course  =cut
        $allowed=0;  
        $script='</script>'.&Apache::lonmenu::registerurl(1,undef).'<script>';  sub list_symbs {
        $events='onLoad="'.&Apache::lonmenu::loadevents.      my ($r) = @_;
            '" onUnload="'.&Apache::lonmenu::unloadevents.'"';  
     }      my $type = &Apache::loncommon::course_type();
       $r->print(&Apache::loncommon::start_page('Symb List'));
 # get course data      $r->print(&Apache::lonhtmlcommon::breadcrumbs('Symb List'));
     my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};      my $navmap = Apache::lonnavmaps::navmap->new();
     my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};      if (!defined($navmap)) {
           $r->print('<h2>'.&mt('Retrieval of List Failed').'</h2>'.
 # get personal data                    '<div class="LC_error">'.
                      &mt('Unable to retrieve information about course contents').
     my $uname=$env{'user.name'};                    '</div>');
     my $udom=$env{'user.domain'};          &Apache::lonnet::logthis('Symb list failed - could not create navmap object in '.lc($type).':'.$env{'request.course.id'});
     my $plainname=&Apache::lonnet::escape(      } else {
                      &Apache::loncommon::plainname($uname,$udom));          $r->print("<pre>\n");
           foreach my $res ($navmap->retrieveResources()) {
 # graphics settings      $r->print($res->compTitle()."\t".$res->symb()."\n");
           }
     $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");          $r->print("\n</pre>\n");
       }
     my $now=time;      $r->print('<a href="/adm/coursedocs">'.&mt('Return to DOCS').'</a>');
   }
 # print screen  
        my $html=&Apache::lonxml::xmlbegin();  
     $r->print(<<ENDDOCUMENT);  sub verifycontent {
 $html      my ($r) = @_;
 <head>      my $type = &Apache::loncommon::course_type();
 <title>The LearningOnline Network with CAPA</title>     my $loaderror=&Apache::lonnet::overloaderror($r);
 <script>     if ($loaderror) { return $loaderror; }
 $script     $r->print(&Apache::loncommon::start_page('Verify '.$type.' Documents'));
 </script>     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Verify '.$type.' Documents'));
 ENDDOCUMENT     $hashtied=0;
    if ($allowed) {     undef %alreadyseen;
     $r->print(<<ENDNEWSCRIPT);     %alreadyseen=();
 <script>     &tiehash();
 function makenewfolder(targetform,folderseq) {     foreach my $key (keys(%hash)) {
     var foldername=prompt('Name of New Folder','New Folder');         if ($hash{$key}=~/\.(page|sequence)$/) {
     if (foldername) {     if (($key=~/^src_/) && ($alreadyseen{&unescape($hash{$key})})) {
  targetform.importdetail.value=foldername+"="+folderseq;         $r->print('<hr /><span class="LC_error">'.
         targetform.submit();   &mt('The following sequence or page is included more than once in your '.$type.': ').
     }   &unescape($hash{$key}).'</span><br />'.
 }   &mt('Note that grading records for problems included in this sequence or folder will overlap.<hr />'));
      }
 function makenewpage(targetform,folderseq) {         }
     var pagename=prompt('Name of New Page','New Page');         if (($key=~/^src\_(.+)$/) && (!$alreadyseen{&unescape($hash{$key})})) {
     if (pagename) {             &checkonthis($r,$hash{$key},0,$hash{'title_'.$1});
         targetform.importdetail.value=pagename+"="+folderseq;         }
         targetform.submit();     }
     }     &untiehash();
 }     $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;  
     window.open('/adm/rat/extpickframe.html');  
 }  sub devalidateversioncache {
       my $src=shift;
 function makeexamupload() {      &Apache::lonnet::devalidate_cache_new('courseresversion',$env{'request.course.id'}.'_'.
    var title=prompt('Listed Title for the Uploaded Score');    &Apache::lonnet::clutter($src));
    if (title) {   }
     this.document.forms.newexamupload.importdetail.value=  
  title+'=/res/lib/templates/examupload.problem';  sub checkversions {
     this.document.forms.newexamupload.submit();      my ($r) = @_;
    }      my $type = &Apache::loncommon::course_type();
 }      $r->print(&Apache::loncommon::start_page("Check $type Document Versions"));
       $r->print(&Apache::lonhtmlcommon::breadcrumbs("Check $type Document Versions"));
 function makesmppage() {      my $header='';
    var title=prompt('Listed Title for the Page');      my $startsel='';
    if (title) {       my $monthsel='';
     this.document.forms.newsmppg.importdetail.value=      my $weeksel='';
  title+'=/adm/$udom/$uname/$now/smppg';      my $daysel='';
     this.document.forms.newsmppg.submit();      my $allsel='';
    }      my %changes=();
 }      my $starttime=0;
       my $haschanged=0;
 function makesmpproblem() {      my %setversions=&Apache::lonnet::dump('resourceversions',
    var title=prompt('Listed Title for the Problem');    $env{'course.'.$env{'request.course.id'}.'.domain'},
    if (title) {     $env{'course.'.$env{'request.course.id'}.'.num'});
     this.document.forms.newsmpproblem.importdetail.value=  
  title+'=/res/lib/templates/simpleproblem.problem';      $hashtied=0;
     this.document.forms.newsmpproblem.submit();      &tiehash();
    }      my %newsetversions=();
 }      if ($env{'form.setmostrecent'}) {
    $haschanged=1;
 function makebulboard() {   foreach my $key (keys(%hash)) {
    var title=prompt('Listed Title for the Bulletin Board');      if ($key=~/^ids\_(\/res\/.+)$/) {
    if (title) {   $newsetversions{$1}='mostrecent';
     this.document.forms.newbul.importdetail.value=                  &devalidateversioncache($1);
  title+'=/adm/$udom/$uname/$now/bulletinboard';      }
     this.document.forms.newbul.submit();   }
    }      } elsif ($env{'form.setcurrent'}) {
 }   $haschanged=1;
    foreach my $key (keys(%hash)) {
 function makeabout() {      if ($key=~/^ids\_(\/res\/.+)$/) {
    var user=prompt("Enter user\@domain for User's 'About Me' Page");   my $getvers=&Apache::lonnet::getversion($1);
    if (user) {   if ($getvers>0) {
        var comp=new Array();      $newsetversions{$1}=$getvers;
        comp=user.split('\@');      &devalidateversioncache($1);
        if ((typeof(comp[0])!=undefined) && (typeof(comp[1])!=undefined)) {   }
    if ((comp[0]) && (comp[1])) {      }
        this.document.forms.newaboutsomeone.importdetail.value=   }
    'About '+user+'=/adm/'+comp[1]+'/'+comp[0]+'/aboutme';      } elsif ($env{'form.setversions'}) {
        this.document.forms.newaboutsomeone.submit();   $haschanged=1;
    } else {   foreach my $key (keys(%env)) {
                alert("Not a valid user\@domain");      if ($key=~/^form\.set_version_(.+)$/) {
            }   my $src=$1;
        } else {   if (($env{$key}) && ($env{$key} ne $setversions{$src})) {
            alert("Please enter both user and domain in the format user\@domain");       $newsetversions{$src}=$env{$key};
        }      &devalidateversioncache($src);
    }   }
 }      }
    }
 function makeims() {      }
     var caller = document.forms.ims.folder.value;      if ($haschanged) {
     var newlocation = "/adm/imsimportdocs?folder="+caller+"&phase=one";          if (&Apache::lonnet::put('resourceversions',\%newsetversions,
     newWindow = window.open("","IMSimport","HEIGHT=700,WIDTH=750,scrollbars=yes");    $env{'course.'.$env{'request.course.id'}.'.domain'},
     newWindow.location.href = newlocation;    $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 }      $r->print('<h1>'.&mt('Your Version Settings have been Saved').'</h1>');
    } else {
       $r->print('<h1><span class="LC_error">'.&mt('An Error Occured while Attempting to Save your Version Settings').'</span></h1>');
 function finishpick() {   }
     var title=this.document.forms.extimport.title.value;   &mark_hash_old();
     var url=this.document.forms.extimport.url.value;      }
     var form=this.document.forms.extimport.useform.value;      &changewarning($r,'');
     eval      if ($env{'form.timerange'} eq 'all') {
      ('this.document.forms.'+form+'.importdetail.value="'+title+'='+url+  # show all documents
     '";this.document.forms.'+form+'.submit();');   $header=&mt('All Documents in '.$type);
 }   $allsel=1;
    foreach my $key (keys(%hash)) {
 function changename(folderpath,index,oldtitle,container,pagesymb) {      if ($key=~/^ids\_(\/res\/.+)$/) {
     var title=prompt('New Title',oldtitle);   my $src=$1;
     if (title) {   $changes{$src}=1;
  this.document.forms.renameform.title.value=title;      }
  this.document.forms.renameform.cmd.value='rename_'+index;   }
         if (container == 'sequence') {      } else {
     this.document.forms.renameform.folderpath.value=folderpath;  # show documents which changed
         }   %changes=&Apache::lonnet::dump
         if (container == 'page') {   ('versionupdate',$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 $firstkey=(keys(%changes))[0];
         }   unless ($firstkey=~/^error\:/) {
         this.document.forms.renameform.submit();      unless ($env{'form.timerange'}) {
     }   $env{'form.timerange'}=604800;
 }      }
       my $seltext=&mt('during the last').' '.$env{'form.timerange'}.' '
 function removeres(folderpath,index,oldtitle,container,pagesymb) {   .&mt('seconds');
     if (confirm('WARNING: Removing a resource makes associated grades and scores inaccessible!\\nRemove "'+oldtitle+'"?')) {      if ($env{'form.timerange'}==-1) {
  this.document.forms.renameform.cmd.value='del_'+index;   $seltext='since start of course';
         if (container == 'sequence') {   $startsel='selected';
             this.document.forms.renameform.folderpath.value=folderpath;   $env{'form.timerange'}=time;
         }      }
         if (container == 'page') {      $starttime=time-$env{'form.timerange'};
             this.document.forms.renameform.pagepath.value=folderpath;      if ($env{'form.timerange'}==2592000) {
             this.document.forms.renameform.pagesymb.value=pagesymb;   $seltext=&mt('during the last month').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
         }   $monthsel='selected';
         this.document.forms.renameform.submit();      } elsif ($env{'form.timerange'}==604800) {
     }   $seltext=&mt('during the last week').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
 }   $weeksel='selected';
       } elsif ($env{'form.timerange'}==86400) {
 function cutres(folderpath,index,oldtitle,container,pagesymb) {   $seltext=&mt('since yesterday').' ('.&Apache::lonlocal::locallocaltime($starttime).')';
     if (confirm('WARNING: Cutting a resource makes associated grades and scores inaccessible!\\nGrades remain inaccessible if resource is pasted into another folder.\\nCut "'+oldtitle+'"?')) {   $daysel='selected';
  this.document.forms.renameform.cmd.value='cut_'+index;      }
  this.document.forms.renameform.markcopy.value=index;      $header=&mt('Content changed').' '.$seltext;
         if (container == 'sequence') {   } else {
             this.document.forms.renameform.folderpath.value=folderpath;      $header=&mt('No content modifications yet.');
         }   }
         if (container == 'page') {      }
             this.document.forms.renameform.pagepath.value=folderpath;      %setversions=&Apache::lonnet::dump('resourceversions',
             this.document.forms.renameform.pagesymb.value=pagesymb;    $env{'course.'.$env{'request.course.id'}.'.domain'},
         }    $env{'course.'.$env{'request.course.id'}.'.num'});
         this.document.forms.renameform.submit();      my %lt=&Apache::lonlocal::texthash
     }        ('st' => 'Version changes since start of '.$type,
 }         'lm' => 'Version changes since last Month',
          'lw' => 'Version changes since last Week',
 function markcopy(folderpath,index,oldtitle,container,pagesymb) {         'sy' => 'Version changes since Yesterday',
     this.document.forms.renameform.markcopy.value=index;                 'al' => 'All Resources (possibly large output)',
     if (container == 'sequence') {         'sd' => 'Display',
  this.document.forms.renameform.folderpath.value=folderpath;         'fi' => 'File',
     }         'md' => 'Modification Date',
     if (container == 'page') {                 'mr' => 'Most recently published Version',
  this.document.forms.renameform.pagepath.value=folderpath;         've' => 'Version used in '.$type,
  this.document.forms.renameform.pagesymb.value=pagesymb;                 'vu' => 'Set Version to be used in '.$type,
     }  'sv' => 'Set Versions to be used in '.$type.' according to Selections below',
     this.document.forms.renameform.submit();  'sm' => 'Keep all Resources up-to-date with most recent Versions (default)',
 }  'sc' => 'Set all Resource Versions to current Version (Fix Versions)',
          'di' => 'Differences');
 </script>      $r->print(<<ENDHEADERS);
   <form action="/adm/coursedocs" method="post">
 ENDNEWSCRIPT  <input type="hidden" name="versions" value="1" />
   }  <input type="submit" name="setmostrecent" value="$lt{'sm'}" />
 # -------------------------------------------------------------------- Body tag  <input type="submit" name="setcurrent" value="$lt{'sc'}" /><hr />
   $r->print('</head>'.  <select name="timerange">
             &Apache::loncommon::bodytag('Course Documents','',$events,  <option value='all' $allsel>$lt{'al'}</option>
  '','',$showdoc).  <option value="-1" $startsel>$lt{'st'}</option>
     &Apache::loncommon::help_open_menu('','','','',273,'RAT'));  <option value="2592000" $monthsel>$lt{'lm'}</option>
   my %allfiles = ();  <option value="604800" $weeksel>$lt{'lw'}</option>
   my %codebase = ();  <option value="86400" $daysel>$lt{'sy'}</option>
   my ($upload_result,$upload_output);  </select>
   if ($allowed) {  <input type="submit" name="display" value="$lt{'sd'}" />
       if (($env{'form.uploaddoc.filename'}) &&                                               ($env{'form.cmd'}=~/^upload_(\w+)/)) {  <h3>$header</h3>
 # Process file upload - phase one - upload and parse primary file.    <input type="submit" name="setversions" value="$lt{'sv'}" />
           $upload_result = &process_file_upload(\$upload_output,$coursenum,  <table border="0">
  $coursedom,\%allfiles,  ENDHEADERS
  \%codebase,$1);      foreach my $key (sort(keys(%changes))) {
           if ($upload_result eq 'phasetwo') {   if ($changes{$key}>$starttime) {
               $r->print($upload_output);      my ($root,$extension)=($key=~/^(.*)\.(\w+)$/);
           }      my $currentversion=&Apache::lonnet::getversion($key);
       } elsif ($env{'form.phasetwo'}) {      if ($currentversion<0) {
           my %newname = ();   $currentversion=&mt('Could not be determined.');
           my %origname = ();      }
           my %attribs = ();      my $linkurl=&Apache::lonnet::clutter($key);
           my $updateflag = 0;      $r->print(
           my $residx = $env{'form.newidx'};        '<tr><td colspan="5"><br /><br /><font size="+1"><b>'.
           my $primary_url = &Apache::lonnet::unescape($env{'form.primaryurl'});        &Apache::lonnet::gettitle($linkurl).
 # Process file upload - phase two - gather secondary files.                        '</b></font></td></tr>'.
           for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {                        '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
               if ($env{'form.embedded_item_'.$i.'.filename'}) {                        '<td colspan="4">'.
                   my $javacodebase;                        '<a href="'.$linkurl.'" target="cat">'.$linkurl.
                   $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);        '</a></td></tr>'.
                   $origname{$i} = &Apache::lonnet::unescape($env{'form.embedded_orig_'.$i});                        '<tr><td></td>'.
                   if (exists($env{'form.embedded_codebase_'.$i})) {                        '<td title="'.$lt{'md'}.'">'.
                       $javacodebase =  &Apache::lonnet::unescape($env{'form.embedded_codebase_'.$i});          &Apache::lonlocal::locallocaltime(
                       $origname{$i} =~ s#^\Q$javacodebase\E/##;                              &Apache::lonnet::metadata($root.'.'.$extension,
                   }                                                       'lastrevisiondate')
                   my @attributes = ();                                                          ).
                   if ($env{'form.embedded_attrib_'.$i} =~ /:/) {                        '</td>'.
                       @attributes = split/:/,$env{'form.embedded_attrib_'.$i};                        '<td title="'.$lt{'mr'}.'"><span class="LC_nobreak">Most Recent: '.
                   } else {                        '<font size="+1">'.$currentversion.'</font>'.
                       @attributes = ($env{'form.embedded_attrib_'.$i});                        '</span></td>'.
                   }                        '<td title="'.$lt{'ve'}.'"><span class="LC_nobreak">In '.$type.': '.
                   foreach (@attributes) {                        '<font size="+1">');
                       push(@{$attribs{$i}},&Apache::lonnet::unescape($_));  # Used in course
                   }      my $usedversion=$hash{'version_'.$linkurl};
                   if ($javacodebase) {      if (($usedversion) && ($usedversion ne 'mostrecent')) {
                       $codebase{$i} = $javacodebase;   $r->print($usedversion);
                       $codebase{$i} =~ s#/$##;      } else {
                       $updateflag = 1;   $r->print($currentversion);
                   }      }
               }      $r->print('</font></span></td><td title="'.$lt{'vu'}.'">'.
               unless ($newname{$i} eq $origname{$i}) {                        '<span class="LC_nobreak">Use: ');
                   $updateflag = 1;  # Set version
               }      $r->print(&Apache::loncommon::select_form($setversions{$linkurl},
           }        'set_version_'.$linkurl,
 # Process file upload - phase three - modify primary file        ('select_form_order' =>
           if ($updateflag) {         ['',1..$currentversion,'mostrecent'],
               my ($content,$rtncode);         '' => '',
               my $updateflag = 0;         'mostrecent' => 'most recent',
               my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);         map {$_,$_} (1..$currentversion))));
               if ($getstatus eq 'ok') {      $r->print('</span></td></tr><tr><td></td>');
                   foreach my $item (keys %newname) {      my $lastold=1;
                       if ($newname{$item} ne $origname{$item}) {      for (my $prevvers=1;$prevvers<$currentversion;$prevvers++) {
                           my $attrib_regexp = '';   my $url=$root.'.'.$prevvers.'.'.$extension;
                           if (@{$attribs{$item}} > 1) {   if (&Apache::lonnet::metadata($url,'lastrevisiondate')<
                               $attrib_regexp = join('|',@{$attribs{$item}});      $starttime) {
                           } else {      $lastold=$prevvers;
                               $attrib_regexp = $attribs{$item}[0];   }
                           }      }
                           if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {              #
                           }               # Code to figure out how many version entries should go in
                           $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;               # each of the four columns
                       }              my $entries_per_col = 0;
                       if (exists($codebase{$item})) {              my $num_entries = ($currentversion-$lastold);
                           $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i;              if ($num_entries % 4 == 0) {
                       }                  $entries_per_col = $num_entries/4;
                   }              } else {
 # Save edited file.                  $entries_per_col = $num_entries/4 + 1;
                   my $saveresult;              }
                   my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};              my $entries_count = 0;
                   my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};              $r->print('<td valign="top"><font size="-2">');
                   my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);              my $cols_output = 1;
               } else {              for (my $prevvers=$lastold;$prevvers<$currentversion;$prevvers++) {
                   &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);    my $url=$root.'.'.$prevvers.'.'.$extension;
               }   $r->print('<span class="LC_nobreak"><a href="'.&Apache::lonnet::clutter($url).
           }    '">'.&mt('Version').' '.$prevvers.'</a> ('.
       }    &Apache::lonlocal::locallocaltime(
   }                                  &Apache::lonnet::metadata($url,
                                                             'lastrevisiondate')
   unless ($showdoc ||  $upload_result eq 'phasetwo') {                                                              ).
 # -----------------------------------------------------------------------------    ')');
        my %lt=&Apache::lonlocal::texthash(   if (&Apache::loncommon::fileembstyle($extension) eq 'ssi') {
                 'uplm' => 'Upload a new main course document',                      $r->print(' <a href="/adm/diff?filename='.
                 'upls' => 'Upload a new supplemental course document',        &Apache::lonnet::clutter($root.'.'.$extension).
                 'impp' => 'Import a document',        '&versionone='.$prevvers.
                 'pubd' => 'Published documents',        '">'.&mt('Diffs').'</a>');
  'copm' => 'All documents out of a published map into this folder',   }
                 'spec' => 'Special documents',   $r->print('</span><br />');
                 'upld' => 'Upload Document',                  if (++$entries_count % $entries_per_col == 0) {
                 'srch' => 'Search',                      $r->print('</font></td>');
                 'impo' => 'Import',                      if ($cols_output != 4) {
                 'selm' => 'Select Map',                          $r->print('<td valign="top"><font size="-2">');
                 'load' => 'Load Map',                          $cols_output++;
                 'reco' => 'Recover Deleted Resources',                      }
                 'newf' => 'New Folder',                  }
                 'newp' => 'New Composite Page',      }
                 'extr' => 'External Resource',              while($cols_output++ < 4) {
                 'syll' => 'Syllabus',                  $r->print('</font></td><td><font>')
                 'navc' => 'Navigate Contents',              }
                 'sipa' => 'Simple Page',      $r->print('</font></td></tr>'."\n");
                 'sipr' => 'Simple Problem',   }
                 'scuf' => 'Score Upload Form',      }
                 'bull' => 'Bulletin Board',      $r->print('</table></form>');
                 'mypi' => 'My Personal Info',      $r->print('<h1>'.&mt('Done').'.</h1>');
  'abou' => 'About User',  
                 'imsf' => 'Import IMS package',      &untiehash();
                 'file' =>  'File',  }
                 'title' => 'Title',  
                 'comment' => 'Comment',  sub mark_hash_old {
                 'parse' => 'If HTML file, upload embedded images/multimedia files'      my $retie_hash=0;
   );      if ($hashtied) {
 # -----------------------------------------------------------------------------   $retie_hash=1;
     if ($allowed) {   &untiehash();
        my $dumpbut=&dumpbutton();      }
        my $exportbut=&exportbutton();      &tiehash('write');
        my %lt=&Apache::lonlocal::texthash(      $hash{'old'}=1;
  'vc' => 'Verify Content',      &untiehash();
  'cv' => 'Check/Set Resource Versions',      if ($retie_hash) { &tiehash(); }
   );  }
   
        my $folderpath=$env{'form.folderpath'};  sub is_hash_old {
        if (!$folderpath) {      my $untie_hash=0;
    if ($env{'form.folder'} eq '' ||      if (!$hashtied) {
        $env{'form.folder'} eq 'supplemental') {   $untie_hash=1;
        $folderpath='default&'.   &tiehash();
    &Apache::lonnet::escape(&mt('Main Course Documents'));      }
    }      my $return=$hash{'old'};
        }      if ($untie_hash) { &untiehash(); }
        unless ($env{'form.pagepath'}) {      return $return;
            $containertag = '<input type="hidden" name="folderpath" value="" />';  }
            $uploadtag = '<input type="hidden" name="folderpath" value="'.$folderpath.'" />';  
        }  sub changewarning {
       my ($r,$postexec,$message,$url)=@_;
        $r->print(<<ENDCOURSEVERIFY);      if (!&is_hash_old()) { return; }
 <form name="renameform" method="post" action="/adm/coursedocs">      my $pathvar='folderpath';
 <input type="hidden" name="title" />      my $path=&escape($env{'form.folderpath'});
 <input type="hidden" name="cmd" />      if (!defined($url)) {
 <input type="hidden" name="markcopy" />   if (defined($env{'form.pagepath'})) {
 $containertag      $pathvar='pagepath';
 </form>      $path=&escape($env{'form.pagepath'});
 <form name="simpleedit" method="post" action="/adm/coursedocs">      $path.='&amp;pagesymb='.&escape($env{'form.pagesymb'});
 <input type=hidden name="importdetail" value="">   }
 $uploadtag   $url='/adm/coursedocs?'.$pathvar.'='.$path;
 </form>      }
 <form action="/adm/coursedocs" method="post" name="courseverify">      my $course_type = &Apache::loncommon::course_type();
 <table bgcolor="#AAAAAA" width="100%" cellspacing="4" cellpadding="4">      if (!defined($message)) {
 <tr><td bgcolor="#DDDDCC">   $message='Changes will become active for your current session after [_1], or the next time you log in.';
 <input type="submit" name="verify" value="$lt{'vc'}" />$help{'Verify_Content'}      }
 </td><td bgcolor="#DDDDCC">      $r->print("\n\n".
     <input type="submit" name="versions" value="$lt{'cv'}" />$help{'Check_Resource_Versions'}  '<script type="text/javascript">function reinit(tf) { tf.submit();'.$postexec.' }</script>'."\n".
 $dumpbut  '<form name="reinitform" method="post" action="/adm/roles" target="loncapaclient">'.
 $exportbut  '<input type="hidden" name="orgurl" value="'.$url.
 </td></tr></table>  '" /><input type="hidden" name="selectrole" value="1" /><h3><span class="LC_warning">'.
 </form>  &mt($message,' <input type="hidden" name="'.
 ENDCOURSEVERIFY      $env{'request.role'}.'" value="1" /><input type="button" value="'.
        $r->print(&Apache::loncommon::help_open_topic('Docs_Adding_Course_Doc',      &mt('re-initializing '.$course_type).'" onClick="reinit(this.form)" />').
      &mt('Editing the Table of Contents for your Course')));  $help{'Caching'}.'</span></h3></form>'."\n\n");
     }  }
 # --------------------------------------------------------- Standard documents  
     $r->print('<table border=2 cellspacing=4 cellpadding=4>');  
     if (($standard) && ($allowed) && (!$forcesupplement)) {  sub init_breadcrumbs {
  $r->print('<tr><td bgcolor="#BBBBBB">');      my ($form,$text)=@_;
 #  '<h2>'.&mt('Main Course Documents').      &Apache::lonhtmlcommon::clear_breadcrumbs();
 #  ($allowed?' '.$help{'Main_Course_Documents'}:'').'</h2>');      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs",
        my $folder=$env{'form.folder'};      text=>"Edit ".&Apache::loncommon::course_type(),
        if ($folder eq '' || $folder eq 'supplemental') {      faq=>273,
            $folder='default';      bug=>'Instructor Interface',
    $env{'form.folderpath'}='default&'.&Apache::lonnet::escape(&mt('Main Course Documents'));                                              help => 'Docs_Adding_Course_Doc'});
        }      &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/coursedocs?".$form.'=1',
        my $postexec='';      text=>$text,
        if ($folder eq 'default') {      faq=>273,
    $r->print('<script>this.window.name="loncapaclient";</script>');      bug=>'Instructor Interface'});
        } else {  }
            #$postexec='self.close();';  
        }  
        $hadchanges=0;  
        &editor($r,$coursenum,$coursedom,$folder,$allowed,$upload_output);  
        if ($hadchanges) {  sub handler {
    &mark_hash_old()      my $r = shift;
        }      &Apache::loncommon::content_type($r,'text/html');
        &changewarning($r,$postexec);      $r->send_http_header;
        my $folderseq='/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.      return OK if $r->header_only;
                      '.sequence';      my $type = &Apache::loncommon::course_type();
        my $pageseq = '/uploaded/'.$coursedom.'/'.$coursenum.'/default_'.time.  
                      '.page';  
  my $container='sequence';  # --------------------------------------------- Initialize help topics for this
  if ($env{'form.pagepath'}) {      foreach my $topic ('Adding_Course_Doc','Main_Course_Documents',
     $container='page';                 'Adding_External_Resource','Navigate_Content',
  }                 'Adding_Folders','Docs_Overview', 'Load_Map',
  my $readfile='/uploaded/'.$coursedom.'/'.$coursenum.'/'.$folder.'.'.$container;                 'Supplemental','Score_Upload_Form','Adding_Pages',
        $r->print(<<ENDFORM);                 'Importing_LON-CAPA_Resource','Uploading_From_Harddrive',
 <table cellspacing=4 cellpadding=4><tr>                 'Check_Resource_Versions','Verify_Content') {
 <th bgcolor="#DDDDDD">$lt{'uplm'}</th>   $help{$topic}=&Apache::loncommon::help_open_topic('Docs_'.$topic);
 <th bgcolor="#DDDDDD">$lt{'impp'}</th>      }
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>      # Composite help files
 </tr>      $help{'Syllabus'} = &Apache::loncommon::help_open_topic(
 <tr><td bgcolor="#DDDDDD">      'Docs_About_Syllabus,Docs_Editing_Templated_Pages');
 $lt{'file'}:<br />      $help{'Simple Page'} = &Apache::loncommon::help_open_topic(
 <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">      'Docs_About_Simple_Page,Docs_Editing_Templated_Pages');
 <input type="file" name="uploaddoc" size="40">      $help{'Simple Problem'} = &Apache::loncommon::help_open_topic(
 <br />      'Option_Response_Simple');
 $lt{'title'}:<br />      $help{'Bulletin Board'} = &Apache::loncommon::help_open_topic(
 <input type="text" size="50" name="comment">      'Docs_About_Bulletin_Board,Docs_Editing_Templated_Pages');
 $uploadtag      $help{'My Personal Info'} = &Apache::loncommon::help_open_topic(
 <input type="hidden" name="cmd" value="upload_default">    'Docs_About_My_Personal_Info,Docs_Editing_Templated_Pages');
 <br />      $help{'Group Files'} = &Apache::loncommon::help_open_topic('Docs_About_Group_Files');
 <nobr>      $help{'Caching'} = &Apache::loncommon::help_open_topic('Caching');
 <label>$lt{'parse'}?  
 <input type="checkbox" name="parserflag" />  # does this user have privileges to modify docs
 </label>      my $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 </nobr>    if ($allowed && $env{'form.verify'}) {
 <br />        &init_breadcrumbs('verify','Verify Content');
 <br />        &verifycontent($r);
 <nobr>    } elsif ($allowed && $env{'form.listsymbs'}) {
 <input type="submit" value="$lt{'upld'}">        &init_breadcrumbs('listsymbs','List Symbs');
  $help{'Uploading_From_Harddrive'}        &list_symbs($r);
 </nobr>    } elsif ($allowed && $env{'form.docslog'}) {
 </form>        &init_breadcrumbs('docslog','Show Log');
 </td>        &docs_change_log($r);
 <td bgcolor="#DDDDDD">    } elsif ($allowed && $env{'form.versions'}) {
 <form action="/adm/coursedocs" method="post" name="simpleeditdefault">        &init_breadcrumbs('versions','Check/Set Resource Versions');
 $lt{'pubd'}<br />        &checkversions($r);
 $uploadtag    } elsif ($allowed && $env{'form.dumpcourse'}) {
 <input type=button onClick="javascript:groupsearch()" value="$lt{'srch'}">        &init_breadcrumbs('dumpcourse','Dump '.&Apache::loncommon::course_type().' DOCS to Construction Space');
 <nobr>        &dumpcourse($r);
 <input type=button onClick="javascript:groupimport();" value="$lt{'impo'}">    } elsif ($allowed && $env{'form.exportcourse'}) {
 $help{'Importing_LON-CAPA_Resource'}        &init_breadcrumbs('exportcourse','Export '.&Apache::loncommon::course_type().' to IMS');
 </nobr>        &exportcourse($r);
 <p>    } else {
 <hr />  # is this a standard course?
 $lt{'copm'}<br />  
 <input type="text" size="40" name="importmap"><br />      my $standard=($env{'request.course.uri'}=~/^\/uploaded\//);
 <nobr><input type=button       my $forcestandard = 0;
 onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"      my $forcesupplement;
 value="$lt{'selm'}"> <input type="submit" name="loadmap" value="$lt{'load'}">      my $script='';
 $help{'Load_Map'}</nobr>      my $showdoc=0;
 </p>      my $containertag;
 </form>      my $uploadtag;
 <hr />  
 <form action="/adm/groupsort" method="post" name="recover">  
 <input type="button" name="recovermap" onClick="javascript:groupopen('$readfile',1)" value="$lt{'reco'}" />      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 </form>      ['folderpath','pagepath',
 ENDFORM       'pagesymb']);
        unless ($env{'form.pagepath'}) {  # No folderpath, no pagepath, see if we have something stored
    $r->print(<<ENDFORM);      if ((!$env{'form.folderpath'}) && (!$env{'form.pagepath'})) {
 <hr />          &Apache::loncommon::restore_course_settings('docs_folderpath',
 <form action="/adm/coursedocs" method="post" name="newext">                                                {'folderpath' => 'scalar'});
 $uploadtag      }
 <input type=hidden name="importdetail" value="">      if (!$env{'form.folderpath'}) {
 <nobr>          &Apache::loncommon::restore_course_settings('docs_folderpath',
 <input name="newext" type="button" onClick="javascript:makenewext('newext');"                                                {'pagepath' => 'scalar'});
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}      }
 </nobr>      if ($env{'form.pagepath'}) {
 </form>         $env{'form.folderpath'}='';
 <form action="/adm/imsimportdocs" method="post" name="ims">      }
 <input type="hidden" name="folder" value="$folder" />      if ($env{'form.folderpath'} =~ /^supplemental_\d+/) {
 <input name="imsimport" type="button" value="$lt{'imsf'}" onClick="javascript:makeims();" />          $env{'form.folderpath'} = 'supplemental&'.
 </nobr>                                    &escape(&mt('Supplemental '.$type.' Documents')).'&'.
 </form>                                    $env{'form.folderpath'};
 ENDFORM      }
        }      &Apache::loncommon::store_course_settings('docs_folderpath',
        $r->print('</td><td bgcolor="#DDDDDD">');                                                  {'pagepath' => 'scalar',
        unless ($env{'form.pagepath'}) {                                                   'folderpath' => 'scalar'});
            $r->print(<<ENDFORM);      if ($env{'form.folderpath'}) {
 <form action="/adm/coursedocs" method="post" name="newfolder">   my (@folderpath)=split('&',$env{'form.folderpath'});
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   $env{'form.foldername'}=&unescape(pop(@folderpath));
 <input type=hidden name="importdetail" value="">   $env{'form.folder'}=pop(@folderpath);
 <nobr>      }
 <input name="newfolder" type="button"      if ($env{'form.pagepath'}) {
 onClick="javascript:makenewfolder(this.form,'$folderseq');"          my (@pagepath)=split('&',$env{'form.pagepath'});
 value="$lt{'newf'}" />$help{'Adding_Folders'}          $env{'form.pagename'}=&unescape(pop(@pagepath));
 </nobr>          $env{'form.folder'}=pop(@pagepath);
 </form>          $containertag = '<input type="hidden" name="pagepath" value="" />'.
 <form action="/adm/coursedocs" method="post" name="newpage">      '<input type="hidden" name="pagesymb" value="" />';
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />          $uploadtag = '<input type="hidden" name="pagepath" value="'.&HTML::Entities::encode($env{'form.pagepath'},'<>&"').'" />'.
 <input type=hidden name="importdetail" value="">      '<input type="hidden" name="pagesymb" value="'.&HTML::Entities::encode($env{'form.pagesymb'},'<>&"').'" />';
 <nobr>      }
 <input name="newpage" type="button"      if ($r->uri=~/^\/adm\/coursedocs\/showdoc\/(.*)$/) {
 onClick="javascript:makenewpage(this.form,'$pageseq');"         $showdoc='/'.$1;
 value="$lt{'newp'}" />$help{'Adding_Pages'}      }
 </nobr>      unless ($showdoc) { # got called from remote
 </form>         if (($env{'form.folder'}=~/^(?:group|default)_/) ||
 <form action="/adm/coursedocs" method="post" name="newsyl">            ($env{'form.folder'} =~ m:^\d+/(pages|sequences)/:)) {
 $uploadtag             $forcestandard = 1;
 <input type=hidden name="importdetail"          }
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">         $forcesupplement=($env{'form.folder'}=~/^supplemental_/);
 <nobr>  
 <input name="newsyl" type="submit" value="$lt{'syll'}" />          if ($allowed) {
  $help{'Syllabus'}           &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cmd']);
 </nobr>           $script=&Apache::lonratedt::editscript('simple');
 </form>         }
 <form action="/adm/coursedocs" method="post" name="newnav">      } else { # got called in sequence from course
 $uploadtag         $allowed=0;
 <input type=hidden name="importdetail"       }
 value="Navigate Content=/adm/navmaps">  
 <nobr>  # get course data
 <input name="newnav" type="submit" value="$lt{'navc'}" />      my $coursenum=$env{'course.'.$env{'request.course.id'}.'.num'};
 $help{'Navigate_Content'}      my $coursedom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 </nobr>  
 </form>  # get personal data
 <form action="/adm/coursedocs" method="post" name="newsmppg">      my $uname=$env{'user.name'};
 $uploadtag      my $udom=$env{'user.domain'};
 <input type=hidden name="importdetail" value="">      my $plainname=&escape(&Apache::loncommon::plainname($uname,$udom));
 <nobr>  
 <input name="newsmppg" type="button" value="$lt{'sipa'}"  # graphics settings
 onClick="javascript:makesmppage();" /> $help{'Simple Page'}  
 </nobr>      $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
 </form>  
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">      if ($allowed) {
 $uploadtag   $script .= &editing_js($udom,$uname);
 <input type=hidden name="importdetail" value="">      }
 <nobr>  # -------------------------------------------------------------------- Body tag
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"      $script = '<script type="text/javascript">'."\n".$script."\n".'</script>';
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}      my $brcrum = [{href=>"/adm/createuser",text=>"$type Documents"}];
 </nobr>      $r->print(&Apache::loncommon::start_page("$type Documents", $script,
 </form>      {'force_register' => $showdoc,
 <form action="/adm/coursedocs" method="post" name="newexamupload">                                       'bread_crumbs' => $brcrum}).
 $uploadtag        &Apache::loncommon::help_open_menu('','',273,'RAT'));
 <input type=hidden name="importdetail" value="">   
 <nobr>    my %allfiles = ();
 <input name="newexamupload" type="button" value="$lt{'scuf'}"    my %codebase = ();
 onClick="javascript:makeexamupload();" />    my ($upload_result,$upload_output);
 $help{'Score_Upload_Form'}    if ($allowed) {
 </nobr>        if (($env{'form.uploaddoc.filename'}) &&
 </form>    ($env{'form.cmd'}=~/^upload_(\w+)/)) {
 <form action="/adm/coursedocs" method="post" name="newbul">  # Process file upload - phase one - upload and parse primary file.  
 $uploadtag    undef($hadchanges);
 <input type=hidden name="importdetail" value="">            $upload_result = &process_file_upload(\$upload_output,$coursenum,
 <nobr>   $coursedom,\%allfiles,
 <input name="newbulletin" type="button" value="$lt{'bull'}"   \%codebase,$1);
 onClick="javascript:makebulboard();" />    if ($hadchanges) {
 $help{'Bulletin Board'}        &mark_hash_old();
 </nobr>    }
 </form>            if ($upload_result eq 'phasetwo') {
 <form action="/adm/coursedocs" method="post" name="newaboutme">                $r->print($upload_output);
 $uploadtag            }
 <input type=hidden name="importdetail"         } elsif ($env{'form.phasetwo'}) {
 value="$plainname=/adm/$udom/$uname/aboutme">            my %newname = ();
 <nobr>            my %origname = ();
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />            my %attribs = ();
 $help{'My Personal Info'}            my $updateflag = 0;
 </nobr>            my $residx = $env{'form.newidx'};
 </form>            my $primary_url = &unescape($env{'form.primaryurl'});
 <form action="/adm/coursedocs" method="post" name="newaboutsomeone">  # Process file upload - phase two - gather secondary files.
 $uploadtag            for (my $i=0; $i<$env{'form.phasetwo'}; $i++) {
 <input type=hidden name="importdetail" value="">                if ($env{'form.embedded_item_'.$i.'.filename'}) {
 <nobr>                    my $javacodebase;
 <input name="newaboutsomeone" type="button" value="$lt{'abou'}"                     $newname{$i} = &process_secondary_uploads(\$upload_output,$coursedom,$coursenum,'embedded_item_',$i,$residx);
 onClick="javascript:makeabout();" />                    $origname{$i} = &unescape($env{'form.embedded_orig_'.$i});
 </nobr>                    if (exists($env{'form.embedded_codebase_'.$i})) {
 </form>                        $javacodebase =  &unescape($env{'form.embedded_codebase_'.$i});  
 ENDFORM                        $origname{$i} =~ s#^\Q$javacodebase\E/##;
        }                    }
        if ($env{'form.pagepath'}) {                    my @attributes = ();
            $r->print(<<ENDBLOCK);                    if ($env{'form.embedded_attrib_'.$i} =~ /:/) {
 <form action="/adm/coursedocs" method="post" name="newsmpproblem">                        @attributes = split(/:/,$env{'form.embedded_attrib_'.$i});
 $uploadtag                    } else {
 <input type=hidden name="importdetail" value="">                        @attributes = ($env{'form.embedded_attrib_'.$i});
 <nobr>                    }
 <input name="newsmpproblem" type="button" value="$lt{'sipr'}"                    foreach my $attr (@attributes) {
 onClick="javascript:makesmpproblem();" />$help{'Simple Problem'}                        push(@{$attribs{$i}},&unescape($attr));
 </nobr>                    }
 </form>                    if ($javacodebase) {
 <form action="/adm/coursedocs" method="post" name="newexamupload">                        $codebase{$i} = $javacodebase;
 $uploadtag                        $codebase{$i} =~ s#/$##;
 <input type=hidden name="importdetail" value="">                        $updateflag = 1;
 <nobr>                    }
 <input name="newexamupload" type="button" value="$lt{'scuf'}"                }
 onClick="javascript:makeexamupload();" />                unless ($newname{$i} eq $origname{$i}) {
 $help{'Score_Upload_Form'}                    $updateflag = 1;
 </nobr>                }
 </form>            }
 ENDBLOCK  # Process file upload - phase three - modify primary file
        }            if ($updateflag) {
        $r->print('</td></tr>'."\n".                my ($content,$rtncode);
 '</table>');                my $updateflag = 0;
        $r->print('</td></tr>');                my $getstatus = &Apache::lonnet::getuploaded('GET',$primary_url,$coursedom,$coursenum,\$content,\$rtncode);
     }                if ($getstatus eq 'ok') {
 # ----------------------------------------------------- Supplemental documents                    foreach my $item (keys(%newname)) {
     if (!$forcestandard) {                        if ($newname{$item} ne $origname{$item}) {
        $r->print('<tr><td bgcolor="#BBBBBB">');                            my $attrib_regexp = '';
 # '<h2>'.&mt('Supplemental Course Documents').                            if (@{$attribs{$item}} > 1) {
 #  ($allowed?' '.$help{'Supplemental'}:'').'</h2>');                                $attrib_regexp = join('|',@{$attribs{$item}});
        my $folder=$env{'form.folder'};                            } else {
        unless ($folder=~/^supplemental/) {                                $attrib_regexp = $attribs{$item}[0];
    $folder='supplemental';                            }
        }                            if ($content =~ m#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#) {
        if ($folder =~ /^supplemental$/ &&                            }
    $env{'form.folderpath'} =~ /^default\&/) {                            $content =~ s#($attrib_regexp\s*=\s*['"]?)\Q$origname{$item}\E(['"]?)#$1$newname{$item}$2#gi;
    $env{'form.folderpath'}='supplemental&'.                        }
        &Apache::lonnet::escape(&mt('Supplemental Course Documents'));                        if (exists($codebase{$item})) {
        }                            $content =~ s/(codebase\s*=\s*["']?)\Q$codebase{$item}\E(["']?)/$1.$2/i; #' stupid emacs
        &editor($r,$coursenum,$coursedom,$folder,$allowed);                        }
        if ($allowed) {                    }
        my $folderseq=  # Save edited file.
                   '/uploaded/'.$coursedom.'/'.$coursenum.'/supplemental_'.time.                    my $saveresult;
                      '.sequence';                    my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
           $r->print(<<ENDSUPFORM);                    my $url = &Apache::lonnet::store_edited_file($primary_url,$content,$docudom,$docuname,\$saveresult);
 <table cellspacing=4 cellpadding=4><tr>                } else {
 <th bgcolor="#DDDDDD">$lt{'upls'}</th>                    &Apache::lonnet::logthis('retrieval of uploaded file - '.$primary_url.' - for editing, failed: '.$getstatus);
 <th bgcolor="#DDDDDD">$lt{'spec'}</th>                }
 </tr>            }
 <tr><td bgcolor="#DDDDDD">        }
 <form action="/adm/coursedocs" method="post" enctype="multipart/form-data">    }
 <input type="file" name="uploaddoc" size="40">  
 <br />    unless ($showdoc ||  $upload_result eq 'phasetwo') {
 <br />  # -----------------------------------------------------------------------------
 <nobr>         my %lt=&Apache::lonlocal::texthash(
 <label>$lt{'parse'}?                  'uplm' => 'Upload a new main '.lc($type).' document',
 <input type="checkbox" name="parserflag" />                  'upls' => 'Upload a new supplemental '.lc($type).' document',
 </label>                  'impp' => 'Import a document',
 </nobr>                  'pubd' => 'Published Documents',
 <br /><br />   'copm' => 'All documents out of a published map into this folder',
 $lt{'comment'}:<br />                  'upld' => 'Upload Document',
 <textarea cols=50 rows=4 name='comment'>                  'srch' => 'Search',
 </textarea>                  'impo' => 'Import',
 <br />   'book' => 'Import Bookmarks',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                  'selm' => 'Select Map',
 <input type="hidden" name="cmd" value="upload_supplemental">                  'load' => 'Load Map',
 <nobr>                  'reco' => 'Recover Deleted Resources',
 <input type="submit" value="$lt{'upld'}">                  'newf' => 'New Folder',
  $help{'Uploading_From_Harddrive'}                  'newp' => 'New Composite Page',
 </nobr>                  'extr' => 'External Resource',
 </form>                  'syll' => 'Syllabus',
 </td>                  'navc' => 'Navigate Contents',
 <td bgcolor="#DDDDDD">                  'sipa' => 'Simple Page',
 <form action="/adm/coursedocs" method="post" name="supnewfolder">                  'sipr' => 'Simple Problem',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                  'drbx' => 'Drop Box',
 <input type=hidden name="importdetail" value="">                  'scuf' => 'Score Upload Form',
 <nobr>                  'bull' => 'Bulletin Board',
 <input name="newfolder" type="button"                  'mypi' => 'My Personal Info',
 onClick="javascript:makenewfolder(this.form,'$folderseq');"                  'grpo' => 'Group Files',
 value="$lt{'newf'}" /> $help{'Adding_Folders'}                  'rost' => 'Course Roster',
 </nobr>   'abou' => 'About User',
 </form>                  'imsf' => 'Import IMS package',
 <form action="/adm/coursedocs" method="post" name="supnewext">                  'file' =>  'File',
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />                  'title' => 'Title',
 <input type=hidden name="importdetail" value="">                  'comment' => 'Comment',
 <nobr>                  'parse' => 'Upload embedded images/multimedia files if HTML file!',
 <input name="newext" type="button"    'nd' => 'New Document',
 onClick="javascript:makenewext('supnewext');"   'pm' => 'Published Map',
 value="$lt{'extr'}" /> $help{'Adding_External_Resource'}   'sd' => 'Special Document',
 </nobr>   'mo' => 'More Options',
 </form>   'hao' => 'Hide all Options'
 <form action="/adm/coursedocs" method="post" name="supnewsyl">    );
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />  # -----------------------------------------------------------------------------
 <input type=hidden name="importdetail"    my $fileupload=(<<FIUP);
 value="Syllabus=/public/$coursedom/$coursenum/syllabus">   $lt{'file'}:<br />
 <nobr>   <input type="file" name="uploaddoc" size="40" />
 <input name="newsyl" type="submit" value="$lt{'syll'}" />  FIUP
 $help{'Syllabus'}  
 </nobr>   my $checkbox=(<<CHBO);
 </form>   <!-- <label>$lt{'parse'}?
 <form action="/adm/coursedocs" method="post" name="subnewaboutme">   <input type="checkbox" name="parserflag" />
 <input type="hidden" name="folderpath" value="$env{'form.folderpath'}" />   </label> -->
 <input type=hidden name="importdetail"    <label>
 value="$plainname=/adm/$udom/$uname/aboutme">   <input type="checkbox" name="parserflag" checked="checked" /> $lt{'parse'}
 <nobr>   </label>
 <input name="newaboutme" type="submit" value="$lt{'mypi'}" />  CHBO
 $help{'My Personal Info'}  
 </nobr>   my $fileuploadform=(<<FUFORM);
 </form>   <form name="uploaddocument" action="/adm/coursedocs" method="post" enctype="multipart/form-data">
 </td></tr>   $fileupload
 </table></td></tr>   <br />
 ENDSUPFORM   $lt{'title'}:<br />
        }   <input type="text" size="50" name="comment" />
     }   $uploadtag
     if ($allowed) {   <input type="hidden" name="cmd" value="upload_default" />
  $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>');   <br />
     }   <span class="LC_nobreak">
     $r->print('</table>');   $checkbox
   } else {   </span>
       unless ($upload_result eq 'phasetwo') {   <br />
 # -------------------------------------------------------- This is showdoc mode   <br />
           $r->print("<h1>".&mt('Uploaded Document').' - '.   <span class="LC_nobreak">
  &Apache::lonnet::gettitle($r->uri).'</h1><p>'.   <input type="submit" value="$lt{'upld'}" />
 &mt('It is recommended that you use an up-to-date virus scanner before handling this file.')."</p><p><table>".   $help{'Uploading_From_Harddrive'}
           &entryline(0,&mt("Click to download or use your browser's Save Link function"),$showdoc).'</table></p>');   </span>
       }   </form>
   }  FUFORM
  }  
  $r->print('</body></html>');   my $simpleeditdefaultform=(<<SEDFFORM);
  return OK;   <form action="/adm/coursedocs" method="post" name="simpleeditdefault">
 }    $lt{'pubd'}<br />
    $uploadtag
 1;   <input type="button" onClick="javascript:groupsearch()" value="$lt{'srch'}" />
 __END__   <br />
    <span class="LC_nobreak">
    <input type="button" onClick="javascript:groupimport();" value="$lt{'impo'}" />
    $help{'Importing_LON-CAPA_Resource'}
    </span>
    <br />
    <input type="button" onClick="javascript:groupopen(0,1,1);" value="$lt{'book'}" />
    <hr />
    <p>
    $lt{'copm'}<br />
    <input type="text" size="40" name="importmap" /><br />
    <span class="LC_nobreak"><input type="button"
    onClick="javascript:openbrowser('simpleeditdefault','importmap','sequence,page','')"
    value="$lt{'selm'}" /> <input type="submit" name="loadmap" value="$lt{'load'}" />
    $help{'Load_Map'}</span>
    </p>
    </form>
   SEDFFORM
   
    my $extresourcesform=(<<ERFORM);
    <form action="/adm/coursedocs" method="post" name="newext">
    $uploadtag
    <input type="hidden" name="importdetail" value="" />
    <span class="LC_nobreak">
    <input name="newext" type="button" onClick="javascript:makenewext('newext');"
    value="$lt{'extr'}" /> $help{'Adding_External_Resource'}
    </span>
    </form>
   ERFORM
   
       if ($allowed) {
    &update_paste_buffer($coursenum,$coursedom);
          my $dumpbut=&dumpbutton();
          my $exportbut=&exportbutton();
          my %lt=&Apache::lonlocal::texthash(
    'vc' => 'Verify Content',
    'cv' => 'Check/Set Resource Versions',
    'ls' => 'List Symbs',
                                            'sl' => 'Show Log'
     );
   
          my $folderpath=$env{'form.folderpath'};
          if (!$folderpath) {
      if ($env{'form.folder'} eq '' ||
          $env{'form.folder'} eq 'supplemental') {
          $folderpath='default&'.
      &escape(&mt('Main '.$type.' Documents'));
      }
          }
          unless ($env{'form.pagepath'}) {
              $containertag = '<input type="hidden" name="folderpath" value="" />';
              $uploadtag = '<input type="hidden" name="folderpath" value="'.&HTML::Entities::encode($folderpath,'<>&"').'" />';
          }
          $r->print(&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.206  
changed lines
  Added in v.1.327


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