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

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


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