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

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


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