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

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


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