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

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


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