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

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

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


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