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

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


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