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

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

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


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