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

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


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