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

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


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