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

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


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