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

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


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