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

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


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