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

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


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