Diff for /loncom/interface/londocs.pm between versions 1.327 and 1.456

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

Removed from v.1.327  
changed lines
  Added in v.1.456


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