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

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

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


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