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

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

Removed from v.1.326  
changed lines
  Added in v.1.387


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