File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.107: download - view: text, annotated - select for diffs
Wed Nov 6 22:36:08 2002 UTC (21 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: version_0_6_2, version_0_6, HEAD
- fixes BUG#918
- allows \n inside <m>

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.107 2002/11/06 22:36:08 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 
   29: # (TeX Content Handler
   30: #
   31: # 05/29/00,05/30,10/11 Gerd Kortemeyer)
   32: #
   33: # 11/28,11/29,11/30,12/01,12/02,12/04,12/23 Gerd Kortemeyer
   34: # 03/23 Guy Albertelli
   35: # 03/24,03/29,04/03 Gerd Kortemeyer
   36: # 04/16/2001 Scott Harrison
   37: # 05/03,05/05,05/07 Gerd Kortemeyer
   38: # 05/28/2001 Scott Harrison
   39: # 06/23,08/07,08/11,8/13,8/17,8/18,8/24,9/26,10/16 Gerd Kortemeyer
   40: # 12/04,12/05 Guy Albertelli
   41: # 12/05 Gerd Kortemeyer
   42: # 12/05 Guy Albertelli
   43: # 12/06,12/07 Gerd Kortemeyer
   44: # 12/15,12/16 Scott Harrison
   45: # 12/25 Gerd Kortemeyer
   46: # YEAR=2002
   47: # 1/16,1/17 Scott Harrison
   48: # 1/17 Gerd Kortemeyer
   49: #
   50: ###
   51: 
   52: ###############################################################################
   53: ##                                                                           ##
   54: ## ORGANIZATION OF THIS PERL MODULE                                          ##
   55: ##                                                                           ##
   56: ## 1. Modules used by this module                                            ##
   57: ## 2. Various subroutines                                                    ##
   58: ## 3. Publication Step One                                                   ##
   59: ## 4. Phase Two                                                              ##
   60: ## 5. Main Handler                                                           ##
   61: ##                                                                           ##
   62: ###############################################################################
   63: 
   64: 
   65: ######################################################################
   66: ######################################################################
   67: 
   68: =pod 
   69: 
   70: =head1 NAME
   71: 
   72: lonpublisher - LON-CAPA publishing handler
   73: 
   74: =head1 SYNOPSIS
   75: 
   76: B<lonpublisher> is used by B<mod_perl> inside B<Apache>.  This is the
   77: invocation by F<loncapa_apache.conf>:
   78: 
   79:   <Location /adm/publish>
   80:   PerlAccessHandler       Apache::lonacc
   81:   SetHandler perl-script
   82:   PerlHandler Apache::lonpublisher
   83:   ErrorDocument     403 /adm/login
   84:   ErrorDocument     404 /adm/notfound.html
   85:   ErrorDocument     406 /adm/unauthorized.html
   86:   ErrorDocument     500 /adm/errorhandler
   87:   </Location>
   88: 
   89: =head1 DESCRIPTION
   90: 
   91: B<lonpublisher> takes the proper steps to add resources to the LON-CAPA
   92: digital library.  This includes updating the metadata table in the
   93: LON-CAPA database.
   94: 
   95: B<lonpublisher> is many things to many people.  
   96: 
   97: This module publishes a file.  This involves gathering metadata,
   98: versioning the file, copying file from construction space to
   99: publication space, and copying metadata from construction space
  100: to publication space.
  101: 
  102: =head2 SUBROUTINES
  103: 
  104: Many of the undocumented subroutines implement various magical
  105: parsing shortcuts.
  106: 
  107: =over 4
  108: 
  109: =cut
  110: 
  111: ######################################################################
  112: ######################################################################
  113: 
  114: 
  115: package Apache::lonpublisher;
  116: 
  117: # ------------------------------------------------- modules used by this module
  118: use strict;
  119: use Apache::File;
  120: use File::Copy;
  121: use Apache::Constants qw(:common :http :methods);
  122: use HTML::LCParser;
  123: use Apache::lonxml;
  124: use Apache::lonhomework;
  125: use Apache::loncacc;
  126: use DBI;
  127: use Apache::lonnet();
  128: use Apache::loncommon();
  129: use Apache::lonmysql;
  130: use vars qw(%metadatafields %metadatakeys);
  131: 
  132: my %addid;
  133: my %nokey;
  134: 
  135: my $docroot;
  136: 
  137: my $cuname;
  138: my $cudom;
  139: 
  140: =pod
  141: 
  142: =item B<metaeval>
  143: 
  144: Evaluates a string that contains metadata.  This subroutine
  145: stores values inside I<%metadatafields> and I<%metadatakeys>.
  146: The hash key is a I<$unikey> corresponding to a unique id
  147: that is descriptive of the parser location inside the XML tree.
  148: 
  149: Parameters:
  150: 
  151: =over 4
  152: 
  153: =item I<$metastring>
  154: 
  155: A string that contains metadata.
  156: 
  157: =back
  158: 
  159: Returns:
  160: 
  161: nothing
  162: 
  163: =cut
  164: 
  165: #########################################
  166: #########################################
  167: sub metaeval {
  168:     my $metastring=shift;
  169:    
  170:         my $parser=HTML::LCParser->new(\$metastring);
  171:         my $token;
  172:         while ($token=$parser->get_token) {
  173:            if ($token->[0] eq 'S') {
  174: 	      my $entry=$token->[1];
  175:               my $unikey=$entry;
  176:               if (defined($token->[2]->{'package'})) { 
  177:                   $unikey.='_package_'.$token->[2]->{'package'};
  178:               } 
  179:               if (defined($token->[2]->{'part'})) { 
  180:                  $unikey.='_'.$token->[2]->{'part'}; 
  181: 	      }
  182:               if (defined($token->[2]->{'id'})) { 
  183:                   $unikey.='_'.$token->[2]->{'id'};
  184:               } 
  185:               if (defined($token->[2]->{'name'})) { 
  186:                  $unikey.='_'.$token->[2]->{'name'}; 
  187: 	      }
  188:               foreach (@{$token->[3]}) {
  189: 		  $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
  190:                   if ($metadatakeys{$unikey}) {
  191: 		      $metadatakeys{$unikey}.=','.$_;
  192:                   } else {
  193:                       $metadatakeys{$unikey}=$_;
  194:                   }
  195:               }
  196:               if ($metadatafields{$unikey}) {
  197: 		  my $newentry=$parser->get_text('/'.$entry);
  198:                   unless (($metadatafields{$unikey}=~/$newentry/) ||
  199:                           ($newentry eq '')) {
  200:                      $metadatafields{$unikey}.=', '.$newentry;
  201: 		  }
  202: 	      } else {
  203:                  $metadatafields{$unikey}=$parser->get_text('/'.$entry);
  204:               }
  205:           }
  206:        }
  207: }
  208: 
  209: #########################################
  210: #########################################
  211: 
  212: =pod
  213: 
  214: =item B<metaread>
  215: 
  216: Read a metadata file
  217: 
  218: Parameters:
  219: 
  220: =over
  221: 
  222: =item I<$logfile>
  223: 
  224: File output stream to output errors and warnings to.
  225: 
  226: =item I<$fn>
  227: 
  228: File name (including path).
  229: 
  230: =back
  231: 
  232: Returns:
  233: 
  234: =over 4
  235: 
  236: =item Scalar string (if successful)
  237: 
  238: XHTML text that indicates successful reading of the metadata.
  239: 
  240: =back
  241: 
  242: =cut
  243: 
  244: #########################################
  245: #########################################
  246: sub metaread {
  247:     my ($logfile,$fn)=@_;
  248:     unless (-e $fn) {
  249: 	print($logfile 'No file '.$fn."\n");
  250:         return '<br><b>No file:</b> <tt>'.$fn.'</tt>';
  251:     }
  252:     print($logfile 'Processing '.$fn."\n");
  253:     my $metastring;
  254:     {
  255:      my $metafh=Apache::File->new($fn);
  256:      $metastring=join('',<$metafh>);
  257:     }
  258:     &metaeval($metastring);
  259:     return '<br><b>Processed file:</b> <tt>'.$fn.'</tt>';
  260: }
  261: 
  262: #########################################
  263: #########################################
  264: 
  265: sub coursedependencies {
  266:     my $url=&Apache::lonnet::declutter(shift);
  267:     $url=~s/\.meta$//;
  268:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
  269:     my $regexp=$url;
  270:     $regexp=~s/(\W)/\\$1/g;
  271:     $regexp='___'.$regexp.'___course';
  272:     my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
  273: 				       $aauthor,$regexp);
  274:     my %courses=();
  275:     foreach (keys %evaldata) {
  276: 	if ($_=~/^([a-zA-Z0-9]+_[a-zA-Z0-9]+)___.+___course$/) {
  277: 	    $courses{$1}=1;
  278:         }
  279:     }
  280:     return %courses;
  281: }
  282: #########################################
  283: #########################################
  284: 
  285: 
  286: =pod
  287: 
  288: =item Form-field-generating subroutines.
  289: 
  290: For input parameters, these subroutines take in values
  291: such as I<$name>, I<$value> and other form field metadata.
  292: The output (scalar string that is returned) is an XHTML
  293: string which presents the form field (foreseeably inside
  294: <form></form> tags).
  295: 
  296: =over 4
  297: 
  298: =item B<textfield>
  299: 
  300: =item B<hiddenfield>
  301: 
  302: =item B<selectbox>
  303: 
  304: =back
  305: 
  306: =cut
  307: 
  308: #########################################
  309: #########################################
  310: sub textfield {
  311:     my ($title,$name,$value)=@_;
  312:     return "\n<p><b>$title:</b><br>".
  313:            '<input type="text" name="'.$name.'" size=80 value="'.$value.'" />';
  314: }
  315: 
  316: sub hiddenfield {
  317:     my ($name,$value)=@_;
  318:     return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
  319: }
  320: 
  321: sub selectbox {
  322:     my ($title,$name,$value,$functionref,@idlist)=@_;
  323:     my $uctitle=uc($title);
  324:     my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
  325: 	"</b></font><br />".'<select name="'.$name.'">';
  326:     foreach (@idlist) {
  327:         $selout.='<option value=\''.$_.'\'';
  328:         if ($_ eq $value) {
  329: 	    $selout.=' selected>'.&{$functionref}($_).'</option>';
  330: 	}
  331:         else {$selout.='>'.&{$functionref}($_).'</option>';}
  332:     }
  333:     return $selout.'</select>';
  334: }
  335: 
  336: #########################################
  337: #########################################
  338: 
  339: =pod
  340: 
  341: =item B<urlfixup>
  342: 
  343: Fix up a url?  First step of publication
  344: 
  345: =cut
  346: 
  347: #########################################
  348: #########################################
  349: sub urlfixup {
  350:     my ($url,$target)=@_;
  351:     unless ($url) { return ''; }
  352:     #javascript code needs no fixing
  353:     if ($url =~ /^javascript:/i) { return $url; }
  354:     if ($url =~ /^mailto:/i) { return $url; }
  355:     #internal document links need no fixing
  356:     if ($url =~ /^\#/) { return $url; } 
  357:     my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
  358:     foreach (values %Apache::lonnet::hostname) {
  359: 	if ($_ eq $host) {
  360: 	    $url=~s/^http\:\/\///;
  361:             $url=~s/^$host//;
  362:         }
  363:     }
  364:     if ($url=~/^http\:\/\//) { return $url; }
  365:     $url=~s/\~$cuname/res\/$cudom\/$cuname/;
  366:     return $url;
  367: }
  368: 
  369: #########################################
  370: #########################################
  371: 
  372: =pod
  373: 
  374: =item B<absoluteurl>
  375: 
  376: Currently undocumented.
  377: 
  378: =cut
  379: 
  380: #########################################
  381: #########################################
  382: sub absoluteurl {
  383:     my ($url,$target)=@_;
  384:     unless ($url) { return ''; }
  385:     if ($target) {
  386: 	$target=~s/\/[^\/]+$//;
  387:        $url=&Apache::lonnet::hreflocation($target,$url);
  388:     }
  389:     return $url;
  390: }
  391: 
  392: #########################################
  393: #########################################
  394: 
  395: =pod
  396: 
  397: =item B<set_allow>
  398: 
  399: Currently undocumented    
  400: 
  401: =cut
  402: 
  403: #########################################
  404: #########################################
  405: sub set_allow {
  406:     my ($allow,$logfile,$target,$tag,$oldurl)=@_;
  407:     my $newurl=&urlfixup($oldurl,$target);
  408:     my $return_url=$oldurl;
  409:     print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
  410:     if ($newurl ne $oldurl) {
  411: 	$return_url=$newurl;
  412: 	print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
  413:     }
  414:     if (($newurl !~ /^javascript:/i) &&
  415: 	($newurl !~ /^mailto:/i) &&
  416: 	($newurl !~ /^http:/i) &&
  417: 	($newurl !~ /^\#/)) {
  418: 	$$allow{&absoluteurl($newurl,$target)}=1;
  419:     }
  420:     return $return_url
  421: }
  422: 
  423: #########################################
  424: #########################################
  425: 
  426: =pod
  427: 
  428: =item B<get_subscribed_hosts>
  429: 
  430: Currently undocumented    
  431: 
  432: =cut
  433: 
  434: #########################################
  435: #########################################
  436: sub get_subscribed_hosts {
  437:     my ($target)=@_;
  438:     my @subscribed;
  439:     my $filename;
  440:     $target=~/(.*)\/([^\/]+)$/;
  441:     my $srcf=$2;
  442:     opendir(DIR,$1);
  443:     while ($filename=readdir(DIR)) {
  444: 	if ($filename=~/$srcf\.(\w+)$/) {
  445: 	    my $subhost=$1;
  446: 	    if (($subhost ne 'meta' && $subhost ne 'subscription') &&
  447:                 ($subhost ne $Apache::lonnet::perlvar{'lonHostID'})) {
  448: 		push(@subscribed,$subhost);
  449: 	    }
  450: 	}
  451:     }
  452:     closedir(DIR);
  453:     my $sh;
  454:     if ( $sh=Apache::File->new("$target.subscription") ) {
  455: 	&Apache::lonnet::logthis("opened $target.subscription");
  456: 	while (my $subline=<$sh>) {
  457: 	    &Apache::lonnet::logthis("Trying $subline");
  458: 	    if ($subline =~ /(^\w+):/) { 
  459:                 if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) { 
  460:                    push(@subscribed,$1);
  461: 	        }
  462:             } else {
  463: 		&Apache::lonnet::logthis("No Match for $subline");
  464: 	    }
  465: 	}
  466:     } else {
  467: 	&Apache::lonnet::logthis("Unable to open $target.subscription");
  468:     }
  469:     return @subscribed;
  470: }
  471: 
  472: 
  473: #########################################
  474: #########################################
  475: 
  476: =pod
  477: 
  478: =item B<get_max_ids_indices>
  479: 
  480: Currently undocumented    
  481: 
  482: =cut
  483: 
  484: #########################################
  485: #########################################
  486: sub get_max_ids_indices {
  487:     my ($content)=@_;
  488:     my $maxindex=10;
  489:     my $maxid=10;
  490:     my $needsfixup=0;
  491:     my $duplicateids=0;
  492: 
  493:     my %allids;
  494:     my %duplicatedids;
  495: 
  496:     my $parser=HTML::LCParser->new($content);
  497:     my $token;
  498:     while ($token=$parser->get_token) {
  499: 	if ($token->[0] eq 'S') {
  500: 	    my $counter;
  501: 	    if ($counter=$addid{$token->[1]}) {
  502: 		if ($counter eq 'id') {
  503: 		    if (defined($token->[2]->{'id'})) {
  504: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
  505: 			if (exists($allids{$token->[2]->{'id'}})) {
  506: 			    $duplicateids=1;
  507: 			    $duplicatedids{$token->[2]->{'id'}}=1;
  508: 			} else {
  509: 			    $allids{$token->[2]->{'id'}}=1;
  510: 			}
  511: 		    } else {
  512: 			$needsfixup=1;
  513: 		    }
  514: 		} else {
  515: 		    if (defined($token->[2]->{'index'})) {
  516: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
  517: 		    } else {
  518: 			$needsfixup=1;
  519: 		    }
  520: 		}
  521: 	    }
  522: 	}
  523:     }
  524:     return ($needsfixup,$maxid,$maxindex,$duplicateids,
  525: 	    (keys(%duplicatedids)));
  526: }
  527: 
  528: #########################################
  529: #########################################
  530: 
  531: =pod
  532: 
  533: =item B<get_all_text_unbalanced>
  534: 
  535: Currently undocumented    
  536: 
  537: =cut
  538: 
  539: #########################################
  540: #########################################
  541: sub get_all_text_unbalanced {
  542:     #there is a copy of this in lonxml.pm
  543:     my($tag,$pars)= @_;
  544:     my $token;
  545:     my $result='';
  546:     $tag='<'.$tag.'>';
  547:     while ($token = $$pars[-1]->get_token) {
  548: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  549: 	    $result.=$token->[1];
  550: 	} elsif ($token->[0] eq 'PI') {
  551: 	    $result.=$token->[2];
  552: 	} elsif ($token->[0] eq 'S') {
  553: 	    $result.=$token->[4];
  554: 	} elsif ($token->[0] eq 'E')  {
  555: 	    $result.=$token->[2];
  556: 	}
  557: 	if ($result =~ /(.*)\Q$tag\E(.*)/s) {
  558: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
  559: 	    #&Apache::lonnet::logthis('Result is :'.$1);
  560: 	    $result=$1;
  561: 	    my $redo=$tag.$2;
  562: 	    push (@$pars,HTML::LCParser->new(\$redo));
  563: 	    $$pars[-1]->xml_mode('1');
  564: 	    last;
  565: 	}
  566:     }
  567:     return $result
  568: }
  569: 
  570: #########################################
  571: #########################################
  572: 
  573: =pod
  574: 
  575: =item B<fix_ids_and_indices>
  576: 
  577: Currently undocumented    
  578: 
  579: =cut
  580: 
  581: #########################################
  582: #########################################
  583: #Arguably this should all be done as a lonnet::ssi instead
  584: sub fix_ids_and_indices {
  585:     my ($logfile,$source,$target)=@_;
  586: 
  587:     my %allow;
  588:     my $content;
  589:     {
  590: 	my $org=Apache::File->new($source);
  591: 	$content=join('',<$org>);
  592:     }
  593: 
  594:     my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
  595: 	&get_max_ids_indices(\$content);
  596: 
  597:     print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
  598: 			   join(', ',@duplicatedids));
  599:     if ($duplicateids) {
  600: 	print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
  601: 	my $outstring='<font color="red">Unable to publish file, it contains duplicated ID(s), ID(s) need to be unique. The duplicated ID(s) are: '.join(', ',@duplicatedids).'</font>';
  602: 	return ($outstring,1);
  603:     }
  604:     if ($needsfixup) {
  605: 	print $logfile "Needs ID and/or index fixup\n".
  606: 	    "Max ID   : $maxid (min 10)\n".
  607:                 "Max Index: $maxindex (min 10)\n";
  608:     }
  609:     my $outstring='';
  610:     my @parser;
  611:     $parser[0]=HTML::LCParser->new(\$content);
  612:     $parser[-1]->xml_mode(1);
  613:     my $token;
  614:     while (@parser) {
  615: 	while ($token=$parser[-1]->get_token) {
  616: 	    if ($token->[0] eq 'S') {
  617: 		my $counter;
  618: 		my $tag=$token->[1];
  619: 		my $lctag=lc($tag);
  620: 		if ($lctag eq 'allow') {
  621: 		    $allow{$token->[2]->{'src'}}=1;
  622: 		    next;
  623: 		}
  624: 		my %parms=%{$token->[2]};
  625: 		$counter=$addid{$tag};
  626: 		if (!$counter) { $counter=$addid{$lctag}; }
  627: 		if ($counter) {
  628: 		    if ($counter eq 'id') {
  629: 			unless (defined($parms{'id'})) {
  630: 			    $maxid++;
  631: 			    $parms{'id'}=$maxid;
  632: 			    print $logfile 'ID: '.$tag.':'.$maxid."\n";
  633: 			}
  634: 		    } elsif ($counter eq 'index') {
  635: 			unless (defined($parms{'index'})) {
  636: 			    $maxindex++;
  637: 			    $parms{'index'}=$maxindex;
  638: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
  639: 			}
  640: 		    }
  641: 		}
  642: 		foreach my $type ('src','href','background','bgimg') {
  643: 		    foreach my $key (keys(%parms)) {
  644: 			if ($key =~ /^$type$/i) {
  645: 			    $parms{$key}=&set_allow(\%allow,$logfile,
  646: 						    $target,$tag,
  647: 						    $parms{$key});
  648: 			}
  649: 		    }
  650: 		}
  651: 		# probably a <randomlabel> image type <label>
  652: 		if ($lctag eq 'label' && defined($parms{'description'})) {
  653: 		    my $next_token=$parser[-1]->get_token();
  654: 		    if ($next_token->[0] eq 'T') {
  655: 			$next_token->[1]=&set_allow(\%allow,$logfile,
  656: 						    $target,$tag,
  657: 						    $next_token->[1]);
  658: 		    }
  659: 		    $parser[-1]->unget_token($next_token);
  660: 		}
  661: 		if ($lctag eq 'applet') {
  662: 		    my $codebase='';
  663: 		    if (defined($parms{'codebase'})) {
  664: 			my $oldcodebase=$parms{'codebase'};
  665: 			unless ($oldcodebase=~/\/$/) {
  666: 			    $oldcodebase.='/';
  667: 			}
  668: 			$codebase=&urlfixup($oldcodebase,$target);
  669: 			$codebase=~s/\/$//;    
  670: 			if ($codebase ne $oldcodebase) {
  671: 			    $parms{'codebase'}=$codebase;
  672: 			    print $logfile 'URL codebase: '.$tag.':'.
  673: 				$oldcodebase.' - '.
  674: 				    $codebase."\n";
  675: 			}
  676: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
  677: 		    } else {
  678: 			foreach ('archive','code','object') {
  679: 			    if (defined($parms{$_})) {
  680: 				my $oldurl=$parms{$_};
  681: 				my $newurl=&urlfixup($oldurl,$target);
  682: 				$newurl=~s/\/[^\/]+$/\/\*/;
  683: 				print $logfile 'Allow: applet '.$_.':'.
  684: 				    $oldurl.' allows '.
  685: 					$newurl."\n";
  686: 				$allow{&absoluteurl($newurl,$target)}=1;
  687: 			    }
  688: 			}
  689: 		    }
  690: 		}
  691: 		my $newparmstring='';
  692: 		my $endtag='';
  693: 		foreach (keys %parms) {
  694: 		    if ($_ eq '/') {
  695: 			$endtag=' /';
  696: 		    } else { 
  697: 			my $quote=($parms{$_}=~/\"/?"'":'"');
  698: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
  699: 		    }
  700: 		}
  701: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  702: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
  703: 		if ($lctag eq 'm') {
  704: 		    $outstring.=&get_all_text_unbalanced('/m',\@parser);
  705: 		}
  706: 	    } elsif ($token->[0] eq 'E') {
  707: 		if ($token->[2]) {
  708: 		    unless ($token->[1] eq 'allow') {
  709: 			$outstring.='</'.$token->[1].'>';
  710: 		    }
  711: 		}
  712: 	    } else {
  713: 		$outstring.=$token->[1];
  714: 	    }
  715: 	}
  716: 	pop(@parser);
  717:     }
  718: 
  719:     if ($needsfixup) {
  720: 	print $logfile "End of ID and/or index fixup\n".
  721: 	    "Max ID   : $maxid (min 10)\n".
  722: 		"Max Index: $maxindex (min 10)\n";
  723:     } else {
  724: 	print $logfile "Does not need ID and/or index fixup\n";
  725:     }
  726: 
  727:     return ($outstring,0,%allow);
  728: }
  729: 
  730: #########################################
  731: #########################################
  732: 
  733: =pod
  734: 
  735: =item B<store_metadata>
  736: 
  737: Store the metadata in the metadata table in the loncapa database.
  738: Uses lonmysql to access the database.
  739: 
  740: Inputs: \%metadata
  741: 
  742: Returns: (error,status).  error is undef on success, status is undef on error.
  743: 
  744: =cut
  745: 
  746: #########################################
  747: #########################################
  748: sub store_metadata {
  749:     my %metadata = %{shift()};
  750:     my $error;
  751:     # Determine if the table exists
  752:     my $status = &Apache::lonmysql::check_table('metadata');
  753:     if (! defined($status)) {
  754:         $error='<font color="red">WARNING: Cannot connect to '.
  755:             'database!</font>';
  756:         &Apache::lonnet::logthis($error);
  757:         return ($error,undef);
  758:     }
  759:     if ($status == 0) {
  760:         # It would be nice to actually create the table....
  761:         $error ='<font color="red">WARNING: The metadata table does not '.
  762:             'exist in the LON-CAPA database.</font>';
  763:         &Apache::lonnet::logthis($error);
  764:         return ($error,undef);
  765:     }
  766:     # Remove old value from table
  767:     $status = &Apache::lonmysql::remove_from_table
  768:         ('metadata','url',$metadata{'url'});
  769:     if (! defined($status)) {
  770:         $error = '<font color="red">Error when removing old values from '.
  771:             'metadata table in LON-CAPA database.</font>';
  772:         &Apache::lonnet::logthis($error);
  773:         return ($error,undef);
  774:     }
  775:     # Store data in table.
  776:     $status = &Apache::lonmysql::store_row('metadata',\%metadata);
  777:     if (! defined($status)) {
  778:         $error='<font color="red">Error occured storing new values in '.
  779:             'metadata table in LON-CAPA database</font>';
  780:         &Apache::lonnet::logthis($error);
  781:         return ($error,undef);
  782:     }
  783:     return (undef,$status);
  784: }
  785: 
  786: #########################################
  787: #########################################
  788: 
  789: =pod
  790: 
  791: =item B<publish>
  792: 
  793: This is the workhorse function of this module.  This subroutine generates
  794: backup copies, performs any automatic processing (prior to publication,
  795: especially for rat and ssi files),
  796: 
  797: I<Additional documentation needed.>
  798: 
  799: =cut
  800: 
  801: #########################################
  802: #########################################
  803: sub publish {
  804: 
  805:     my ($source,$target,$style,$batch)=@_;
  806:     my $logfile;
  807:     my $scrout='';
  808:     my $allmeta='';
  809:     my $content='';
  810:     my %allow=();
  811: 
  812:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  813: 	return 
  814:          '<font color=red>No write permission to user directory, FAIL</font>';
  815:     }
  816:     print $logfile 
  817: "\n\n================= Publish ".localtime()." Phase One  ================\n";
  818: 
  819:     if (($style eq 'ssi') || ($style eq 'rat')) {
  820: # ------------------------------------------------------- This needs processing
  821: 
  822: # ----------------------------------------------------------------- Backup Copy
  823: 	my $copyfile=$source.'.save';
  824:         if (copy($source,$copyfile)) {
  825: 	    print $logfile "Copied original file to ".$copyfile."\n";
  826:         } else {
  827: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
  828:           return "<font color=red>Failed to write backup copy, $!,FAIL</font>";
  829:         }
  830: # ------------------------------------------------------------- IDs and indices
  831: 	
  832: 	my ($outstring,$error);
  833: 	($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
  834: 							$target);
  835: 	if ($error) { return $outstring; }
  836: # ------------------------------------------------------------ Construct Allows
  837:     
  838: 	$scrout.='<h3>Dependencies</h3>';
  839:         my $allowstr='';
  840:         foreach (sort(keys(%allow))) {
  841: 	   my $thisdep=$_;
  842: 	   if ($thisdep !~ /[^\s]/) { next; }
  843:            unless ($style eq 'rat') { 
  844:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
  845: 	   }
  846:            $scrout.='<br>';
  847:            unless ($thisdep=~/\*/) {
  848: 	       $scrout.='<a href="'.$thisdep.'">';
  849:            }
  850:            $scrout.='<tt>'.$thisdep.'</tt>';
  851:            unless ($thisdep=~/\*/) {
  852: 	       $scrout.='</a>';
  853:                if (
  854:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
  855:                                             $thisdep.'.meta') eq '-1') {
  856: 		   $scrout.= ' - <font color="red">Currently not available'.
  857: 		       '</font>';
  858:                } else {
  859:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
  860:                              &Apache::lonnet::declutter($thisdep).'___usage'
  861:                                  => time);
  862:                    $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
  863:                    if ((defined($1)) && (defined($2))) {
  864:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
  865: 					   $1,$2);
  866: 		   }
  867: 	       }
  868:            }
  869:         }
  870:         $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
  871: 
  872: 	#Encode any High ASCII characters
  873: 	$outstring=&HTML::Entities::encode($outstring,"\200-\377");
  874: # ------------------------------------------------------------- Write modified.
  875: 
  876:         {
  877:           my $org;
  878:           unless ($org=Apache::File->new('>'.$source)) {
  879:              print $logfile "No write permit to $source\n";
  880:              return 
  881: 		 '<font color="red">No write permission to '.$source.
  882: 		 ', FAIL</font>';
  883: 	  }
  884:           print($org $outstring);
  885:         }
  886: 	  $content=$outstring;
  887: 
  888:     }
  889: # -------------------------------------------- Initial step done, now metadata.
  890: 
  891: # --------------------------------------- Storage for metadata keys and fields.
  892: 
  893:      %metadatafields=();
  894:      %metadatakeys=();
  895:      
  896:      my %oldparmstores=();
  897:      
  898:     unless ($batch) {
  899:      $scrout.='<h3>Metadata Information ' .
  900:        Apache::loncommon::help_open_topic("Metadata_Description")
  901:        . '</h3>';
  902:     }
  903: 
  904: # ------------------------------------------------ First, check out environment
  905:      unless (-e $source.'.meta') {
  906:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
  907: 	                          $ENV{'environment.middlename'}.' '.
  908: 		                  $ENV{'environment.lastname'}.' '.
  909: 		                  $ENV{'environment.generation'};
  910:         $metadatafields{'author'}=~s/\s+/ /g;
  911:         $metadatafields{'author'}=~s/\s+$//;
  912:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
  913: 
  914: # ------------------------------------------------ Check out directory hierachy
  915: 
  916:         my $thisdisfn=$source;
  917:         $thisdisfn=~s/^\/home\/$cuname\///;
  918: 
  919:         my @urlparts=split(/\//,$thisdisfn);
  920:         $#urlparts--;
  921: 
  922:         my $currentpath='/home/'.$cuname.'/';
  923: 
  924:         foreach (@urlparts) {
  925: 	    $currentpath.=$_.'/';
  926:             $scrout.=&metaread($logfile,$currentpath.'default.meta');
  927:         }
  928: 
  929: # ------------------- Clear out parameters and stores (there should not be any)
  930: 
  931:         foreach (keys %metadatafields) {
  932: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  933: 		delete $metadatafields{$_};
  934:             }
  935:         }
  936: 
  937:     } else {
  938: # ---------------------- Read previous metafile, remember parameters and stores
  939: 
  940:         $scrout.=&metaread($logfile,$source.'.meta');
  941: 
  942:         foreach (keys %metadatafields) {
  943: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  944:                 $oldparmstores{$_}=1;
  945: 		delete $metadatafields{$_};
  946:             }
  947:         }
  948:         
  949:     }
  950: 
  951: # -------------------------------------------------- Parse content for metadata
  952:     if ($style eq 'ssi') {
  953:         my $oldenv=$ENV{'request.uri'};
  954: 
  955:         $ENV{'request.uri'}=$target;
  956:         $allmeta=Apache::lonxml::xmlparse(undef,'meta',$content);
  957:         $ENV{'request.uri'}=$oldenv;
  958: 
  959:         &metaeval($allmeta);
  960:     }
  961: # ---------------- Find and document discrepancies in the parameters and stores
  962: 
  963:         my $chparms='';
  964:         foreach (sort keys %metadatafields) {
  965: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  966:                 unless ($_=~/\.\w+$/) { 
  967:                    unless ($oldparmstores{$_}) {
  968: 		      print $logfile 'New: '.$_."\n";
  969:                       $chparms.=$_.' ';
  970:                    }
  971: 	        }
  972:             }
  973:         }
  974:         if ($chparms) {
  975: 	    $scrout.='<p><b>New parameters or stored values:</b> '.
  976:                      $chparms;
  977:         }
  978: 
  979:         $chparms='';
  980:         foreach (sort keys %oldparmstores) {
  981: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  982:                 unless (($metadatafields{$_.'.name'}) ||
  983:                         ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
  984: 		    print $logfile 'Obsolete: '.$_."\n";
  985:                     $chparms.=$_.' ';
  986:                 }
  987:             }
  988:         }
  989:         if ($chparms) {
  990: 	    $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
  991:                      $chparms;
  992:         }
  993: 
  994: # ------------------------------------------------------- Now have all metadata
  995: 
  996:         my %keywords=();
  997:         
  998: 	if (length($content)<500000) {
  999: 	    my $textonly=$content;
 1000:             $textonly=~s/\<script[^\<]+\<\/script\>//g;
 1001:             $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
 1002:             $textonly=~s/\<[^\>]*\>//g;
 1003:             $textonly=~tr/A-Z/a-z/;
 1004:             $textonly=~s/[\$\&][a-z]\w*//g;
 1005:             $textonly=~s/[^a-z\s]//g;
 1006: 
 1007:             foreach ($textonly=~m/(\w+)/g) {
 1008: 		unless ($nokey{$_}) {
 1009:                    $keywords{$_}=1;
 1010:                 } 
 1011:             }
 1012:         }
 1013: 
 1014:             
 1015:             foreach (split(/\W+/,$metadatafields{'keywords'})) {
 1016: 		$keywords{$_}=1;
 1017:             }
 1018: # --------------------------------------------------- Now we also have keywords
 1019: # =============================================================================
 1020: # INTERACTIVE MODE
 1021: #
 1022:    unless ($batch) {
 1023:         $scrout.=
 1024:      '<form name="pubform" action="/adm/publish" method="post">'.
 1025:        '<p><input type="submit" value="Finalize Publication" /></p>'.
 1026:           &hiddenfield('phase','two').
 1027:           &hiddenfield('filename',$ENV{'form.filename'}).
 1028: 	  &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
 1029:           &hiddenfield('dependencies',join(',',keys %allow)).
 1030:           &textfield('Title','title',$metadatafields{'title'}).
 1031:           &textfield('Author(s)','author',$metadatafields{'author'}).
 1032: 	  &textfield('Subject','subject',$metadatafields{'subject'});
 1033: 
 1034: # --------------------------------------------------- Scan content for keywords
 1035: 
 1036:         my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
 1037: 	my $keywordout=<<"END";
 1038: <script>
 1039: function checkAll(field)
 1040: {
 1041:     for (i = 0; i < field.length; i++)
 1042:         field[i].checked = true ;
 1043: }
 1044: 
 1045: function uncheckAll(field)
 1046: {
 1047:     for (i = 0; i < field.length; i++)
 1048:         field[i].checked = false ;
 1049: }
 1050: </script>
 1051: <p><b>Keywords: $keywords_help</b> 
 1052: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)"> 
 1053: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)"> 
 1054: <br />
 1055: END
 1056:         $keywordout.='<table border=2><tr>';
 1057:         my $colcount=0;
 1058: 
 1059:             foreach (sort keys %keywords) {
 1060:                 $keywordout.='<td><input type=checkbox name="keywords" value="'.$_.'"';
 1061:                 if ($metadatafields{'keywords'}) {
 1062:                    if ($metadatafields{'keywords'}=~/$_/) { 
 1063:                       $keywordout.=' checked'; 
 1064:                    }
 1065: 	        } elsif (&Apache::loncommon::keyword($_)) {
 1066: 	            $keywordout.=' checked';
 1067:                 } 
 1068:                 $keywordout.='>'.$_.'</td>';
 1069:                 if ($colcount>10) {
 1070: 		    $keywordout.="</tr><tr>\n";
 1071:                     $colcount=0;
 1072:                 }
 1073:                 $colcount++;
 1074:             }
 1075:         
 1076: 	$keywordout.='</tr></table>';
 1077: 
 1078:         $scrout.=$keywordout;
 1079: 
 1080:         $scrout.=&textfield('Additional Keywords','addkey','');
 1081: 
 1082:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
 1083: 
 1084:         $scrout.=
 1085:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
 1086:               $metadatafields{'abstract'}.'</textarea>';
 1087: 
 1088: 	$source=~/\.(\w+)$/;
 1089: 
 1090: 	$scrout.=&hiddenfield('mime',$1);
 1091: 
 1092:         $scrout.=&selectbox('Language','language',
 1093:                             $metadatafields{'language'},
 1094: 			    \&Apache::loncommon::languagedescription,
 1095: 			    (&Apache::loncommon::languageids),
 1096: 			     );
 1097: 
 1098:         unless ($metadatafields{'creationdate'}) {
 1099: 	    $metadatafields{'creationdate'}=time;
 1100:         }
 1101:         $scrout.=&hiddenfield('creationdate',
 1102:               &Apache::loncommon::unsqltime($metadatafields{'creationdate'}));
 1103: 
 1104:         $scrout.=&hiddenfield('lastrevisiondate',time);
 1105: 
 1106: 			   
 1107: 	$scrout.=&textfield('Publisher/Owner','owner',
 1108:                             $metadatafields{'owner'});
 1109: 
 1110: # -------------------------------------------------- Correct copyright for rat.
 1111:     if ($style eq 'rat') {
 1112: 	if ($metadatafields{'copyright'} eq 'public') { 
 1113: 	    delete $metadatafields{'copyright'};
 1114: 	}
 1115:         $scrout.=&selectbox('Copyright/Distribution','copyright',
 1116:                             $metadatafields{'copyright'},
 1117: 			    \&Apache::loncommon::copyrightdescription,
 1118: 		     (grep !/^public$/,(&Apache::loncommon::copyrightids)));
 1119:     }
 1120:     else {
 1121:         $scrout.=&selectbox('Copyright/Distribution','copyright',
 1122:                             $metadatafields{'copyright'},
 1123: 			    \&Apache::loncommon::copyrightdescription,
 1124: 			     (&Apache::loncommon::copyrightids));
 1125:     }
 1126: 
 1127:     my $copyright_help =
 1128:         Apache::loncommon::help_open_topic('Publishing_Copyright');
 1129:     $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
 1130:     return $scrout.
 1131:         '<p><input type="submit" value="Finalize Publication" /></p></form>';
 1132: # =============================================================================
 1133: # BATCH MODE
 1134: #
 1135:   } else {
 1136: # Transfer metadata directly to environment for stage 2
 1137:     foreach (keys %metadatafields) {
 1138: 	$ENV{'form.'.$_}=$metadatafields{$_};
 1139:     }
 1140:     $ENV{'form.addkey'}='';
 1141:     $ENV{'form.keywords'}='';
 1142:     foreach (keys %keywords) {
 1143:         if ($metadatafields{'keywords'}) {
 1144:            if ($metadatafields{'keywords'}=~/$_/) { 
 1145:               $ENV{'form.keywords'}.=$_.','; 
 1146:            }
 1147: 	} elsif (&Apache::loncommon::keyword($_)) {
 1148: 	    $ENV{'form.keywords'}.=$_.',';
 1149:         } 
 1150:     }
 1151:     $ENV{'form.keywords'}=~s/\,$//;
 1152:     unless ($ENV{'form.creationdate'}) { $ENV{'form.creationdate'}=time; }
 1153:     $ENV{'form.lastrevisiondate'}=time;
 1154:     if ((($style eq 'rat') && ($ENV{'form.copyright'} eq 'public')) ||
 1155:         (!$ENV{'form.copyright'})) { 
 1156: 	$ENV{'form.copyright'}='default';
 1157:     } 
 1158:     $ENV{'form.allmeta'}=&Apache::lonnet::escape($allmeta);
 1159:     return $scrout;
 1160:   }
 1161: }
 1162: 
 1163: #########################################
 1164: #########################################
 1165: 
 1166: =pod 
 1167: 
 1168: =item B<phasetwo>
 1169: 
 1170: Render second interface showing status of publication steps.
 1171: This is publication step two.
 1172: 
 1173: Parameters:
 1174: 
 1175: =over 4
 1176: 
 1177: =item I<$source>
 1178: 
 1179: =item I<$target>
 1180: 
 1181: =item I<$style>
 1182: 
 1183: =item I<$distarget>
 1184: 
 1185: =back
 1186: 
 1187: Returns:
 1188: 
 1189: =over 4
 1190: 
 1191: =item Scalar string
 1192: 
 1193: String contains status (errors and warnings) and information associated with
 1194: the server's attempts at publication.     
 1195: 
 1196: =cut
 1197: 
 1198: #'stupid emacs
 1199: #########################################
 1200: #########################################
 1201: sub phasetwo {
 1202: 
 1203:     my ($r,$source,$target,$style,$distarget,$batch)=@_;
 1204:     $source=~s/\/+/\//g;
 1205:     $target=~s/\/+/\//g;
 1206:     $distarget=~s/\/+/\//g;
 1207:     my $logfile;
 1208:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
 1209: 	return 
 1210:             '<font color=red>No write permission to user directory, FAIL</font>';
 1211:     }
 1212:     print $logfile 
 1213:         "\n================= Publish ".localtime()." Phase Two  ================\n";
 1214:     
 1215:     %metadatafields=();
 1216:     %metadatakeys=();
 1217:     
 1218:     &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
 1219:     
 1220:     $metadatafields{'title'}=$ENV{'form.title'};
 1221:     $metadatafields{'author'}=$ENV{'form.author'};
 1222:     $metadatafields{'subject'}=$ENV{'form.subject'};
 1223:     $metadatafields{'notes'}=$ENV{'form.notes'};
 1224:     $metadatafields{'abstract'}=$ENV{'form.abstract'};
 1225:     $metadatafields{'mime'}=$ENV{'form.mime'};
 1226:     $metadatafields{'language'}=$ENV{'form.language'};
 1227:     $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
 1228:     $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
 1229:     $metadatafields{'owner'}=$ENV{'form.owner'};
 1230:     $metadatafields{'copyright'}=$ENV{'form.copyright'};
 1231:     $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
 1232:     
 1233:     my $allkeywords=$ENV{'form.addkey'};
 1234:     if (exists($ENV{'form.keywords'})) {
 1235:         if (ref($ENV{'form.keywords'})) {
 1236:             $allkeywords .= ','.join(',',@{$ENV{'form.keywords'}});
 1237:         } else {
 1238:             $allkeywords .= ','.$ENV{'form.keywords'};
 1239:         }
 1240:     }
 1241:     $allkeywords=~s/\W+/\,/;
 1242:     $allkeywords=~s/^\,//;
 1243:     $metadatafields{'keywords'}=$allkeywords;
 1244:     
 1245:     {
 1246:         print $logfile "\nWrite metadata file for ".$source;
 1247:         my $mfh;
 1248:         unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
 1249:             return 
 1250:                 '<font color=red>Could not write metadata, FAIL</font>';
 1251:         }
 1252:         foreach (sort keys %metadatafields) {
 1253:             unless ($_=~/\./) {
 1254:                 my $unikey=$_;
 1255:                 $unikey=~/^([A-Za-z]+)/;
 1256:                 my $tag=$1;
 1257:                 $tag=~tr/A-Z/a-z/;
 1258:                 print $mfh "\n\<$tag";
 1259:                 foreach (split(/\,/,$metadatakeys{$unikey})) {
 1260:                     my $value=$metadatafields{$unikey.'.'.$_};
 1261:                     $value=~s/\"/\'\'/g;
 1262:                     print $mfh ' '.$_.'="'.$value.'"';
 1263:                 }
 1264:                 print $mfh '>'.
 1265:                     &HTML::Entities::encode($metadatafields{$unikey})
 1266:                         .'</'.$tag.'>';
 1267:             }
 1268:         }
 1269:         $r->print('<p>Wrote Metadata');
 1270:         print $logfile "\nWrote metadata";
 1271:     }
 1272:     
 1273: # -------------------------------- Synchronize entry with SQL metadata database
 1274: 
 1275:     $metadatafields{'url'} = $distarget;
 1276:     $metadatafields{'version'} = 'current';
 1277:     unless ($metadatafields{'copyright'} eq 'priv') {
 1278:         my ($error,$success) = &store_metadata(\%metadatafields);
 1279:         if ($success) {
 1280:             $r->print('<p>Synchronized SQL metadata database');
 1281:             print $logfile "\nSynchronized SQL metadata database";
 1282:         } else {
 1283:             $r->print($error);
 1284:             print $logfile "\n".$error;
 1285:         }
 1286:     } else {
 1287:         $r->print('<p>Private Publication - did not synchronize database');
 1288:         print $logfile "\nPrivate: Did not synchronize data into ".
 1289:             "SQL metadata database";
 1290:     }
 1291: # ----------------------------------------------------------- Copy old versions
 1292:    
 1293:     if (-e $target) {
 1294:         my $filename;
 1295:         my $maxversion=0;
 1296:         $target=~/(.*)\/([^\/]+)\.(\w+)$/;
 1297:         my $srcf=$2;
 1298:         my $srct=$3;
 1299:         my $srcd=$1;
 1300:         unless ($srcd=~/^\/home\/httpd\/html\/res/) {
 1301:             print $logfile "\nPANIC: Target dir is ".$srcd;
 1302:             return "<font color=red>Invalid target directory, FAIL</font>";
 1303:         }
 1304:         opendir(DIR,$srcd);
 1305:         while ($filename=readdir(DIR)) {
 1306:             if (-l $srcd.'/'.$filename) {
 1307:                 unlink($srcd.'/'.$filename);
 1308:                 unlink($srcd.'/'.$filename.'.meta');
 1309:             } else {
 1310:                 if ($filename=~/$srcf\.(\d+)\.$srct$/) {
 1311:                     $maxversion=($1>$maxversion)?$1:$maxversion;
 1312:                 }
 1313:             }
 1314:         }
 1315:         closedir(DIR);
 1316:         $maxversion++;
 1317:         $r->print('<p>Creating old version '.$maxversion);
 1318:         print $logfile "\nCreating old version ".$maxversion;
 1319:         
 1320:         my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
 1321:         
 1322:         if (copy($target,$copyfile)) {
 1323: 	    print $logfile "Copied old target to ".$copyfile."\n";
 1324:             $r->print('<p>Copied old target file');
 1325:         } else {
 1326: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 1327:             return "<font color=red>Failed to copy old target, $!, FAIL</font>";
 1328:         }
 1329:         
 1330: # --------------------------------------------------------------- Copy Metadata
 1331: 
 1332: 	$copyfile=$copyfile.'.meta';
 1333:         
 1334:         if (copy($target.'.meta',$copyfile)) {
 1335: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
 1336:             $r->print('<p>Copied old metadata')
 1337:         } else {
 1338: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 1339:             if (-e $target.'.meta') {
 1340:                 return 
 1341:                     "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
 1342: 	    }
 1343:         }
 1344:         
 1345:         
 1346:     } else {
 1347:         $r->print('<p>Initial version');
 1348:         print $logfile "\nInitial version";
 1349:     }
 1350: 
 1351: # ---------------------------------------------------------------- Write Source
 1352:     my $copyfile=$target;
 1353:     
 1354:     my @parts=split(/\//,$copyfile);
 1355:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1356:     
 1357:     my $count;
 1358:     for ($count=5;$count<$#parts;$count++) {
 1359:         $path.="/$parts[$count]";
 1360:         if ((-e $path)!=1) {
 1361:             print $logfile "\nCreating directory ".$path;
 1362:             $r->print('<p>Created directory '.$parts[$count]);
 1363:             mkdir($path,0777);
 1364:         }
 1365:     }
 1366:     
 1367:     if (copy($source,$copyfile)) {
 1368:         print $logfile "\nCopied original source to ".$copyfile."\n";
 1369:         $r->print('<p>Copied source file');
 1370:     } else {
 1371:         print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 1372:         return "<font color=red>Failed to copy source, $!, FAIL</font>";
 1373:     }
 1374:     
 1375: # --------------------------------------------------------------- Copy Metadata
 1376: 
 1377:     $copyfile=$copyfile.'.meta';
 1378:     
 1379:     if (copy($source.'.meta',$copyfile)) {
 1380:         print $logfile "\nCopied original metadata to ".$copyfile."\n";
 1381:         $r->print('<p>Copied metadata');
 1382:     } else {
 1383:         print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
 1384:         return 
 1385:             "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
 1386:     }
 1387:     $r->rflush;
 1388: # --------------------------------------------------- Send update notifications
 1389: 
 1390:     my @subscribed=&get_subscribed_hosts($target);
 1391:     foreach my $subhost (@subscribed) {
 1392: 	$r->print('<p>Notifying host '.$subhost.':');$r->rflush;
 1393: 	print $logfile "\nNotifying host ".$subhost.':';
 1394: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 1395: 	$r->print($reply.'<br />');$r->rflush;
 1396: 	print $logfile $reply;
 1397:     }
 1398:     
 1399: # ---------------------------------------- Send update notifications, meta only
 1400: 
 1401:     my @subscribedmeta=&get_subscribed_hosts("$target.meta");
 1402:     foreach my $subhost (@subscribedmeta) {
 1403: 	$r->print('<p>Notifying host for metadata only '.$subhost.':');$r->rflush;
 1404: 	print $logfile "\nNotifying host for metadata only ".$subhost.':';
 1405: 	my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 1406: 					    $subhost);
 1407: 	$r->print($reply.'<br />');$r->rflush;
 1408: 	print $logfile $reply;
 1409:     }
 1410:     
 1411: # --------------------------------------------------- Notify subscribed courses
 1412:     my %courses=&coursedependencies($target);
 1413:     my $now=time;
 1414:     foreach (keys %courses) {
 1415: 	$r->print('<p>Notifying course '.$_.':');$r->rflush;
 1416: 	print $logfile "\nNotifying host ".$_.':';
 1417:         my ($cdom,$cname)=split(/\_/,$_);
 1418: 	my $reply=&Apache::lonnet::cput
 1419:                   ('versionupdate',{$target => $now},$cdom,$cname);
 1420: 	$r->print($reply.'<br />');$r->rflush;
 1421: 	print $logfile $reply;
 1422:     }
 1423: # ------------------------------------------------ Provide link to new resource
 1424:     unless ($batch) {
 1425:         my $thisdistarget=$target;
 1426:         $thisdistarget=~s/^$docroot//;
 1427:         
 1428:         my $thissrc=$source;
 1429:         $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
 1430:         
 1431:         my $thissrcdir=$thissrc;
 1432:         $thissrcdir=~s/\/[^\/]+$/\//;
 1433:         
 1434:         
 1435:         $r->print(
 1436:            '<hr><a href="'.$thisdistarget.'"><font size="+2">'.
 1437:            'View Published Version</font></a>'.
 1438:            '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
 1439:            '<p><a href="'.$thissrcdir.
 1440:                    '"><font size="+2">Back to Source Directory</font></a>');
 1441:     }
 1442: }
 1443: 
 1444: #########################################
 1445: 
 1446: sub batchpublish {
 1447:     my ($r,$srcfile,$targetfile)=@_;
 1448:     $srcfile=~s/\/+/\//g;
 1449:     $targetfile=~s/\/+/\//g;
 1450:     my $thisdisfn=$srcfile;
 1451:     $thisdisfn=~s/\/home\/korte\/public_html\///;
 1452:     $srcfile=~s/\/+/\//g;
 1453: 
 1454:     my $docroot=$r->dir_config('lonDocRoot');
 1455:     my $thisdistarget=$targetfile;
 1456:     $thisdistarget=~s/^$docroot//;
 1457: 
 1458: 
 1459:     undef %metadatafields;
 1460:     undef %metadatakeys;
 1461:      %metadatafields=();
 1462:      %metadatakeys=();
 1463:       $srcfile=~/\.(\w+)$/;
 1464:       my $thistype=$1;
 1465: 
 1466: 
 1467:       my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 1468:      
 1469:     $r->print('<h2>Publishing <tt>'.$thisdisfn.'</tt></h2>');
 1470: 
 1471: # phase one takes
 1472: #  my ($source,$target,$style,$batch)=@_;
 1473:     $r->print('<p>'.&publish($srcfile,$targetfile,$thisembstyle,1).'</p>');
 1474: # phase two takes
 1475: # my ($source,$target,$style,$distarget,batch)=@_;
 1476: # $ENV{'form.allmeta'},$ENV{'form.title'},$ENV{'form.author'},...
 1477:     $r->print('<p>');
 1478:     &phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
 1479:     $r->print('</p>');
 1480:     return '';
 1481: }
 1482: 
 1483: #########################################
 1484: 
 1485: sub publishdirectory {
 1486:     my ($r,$fn,$thisdisfn)=@_;
 1487:     $fn=~s/\/+/\//g;
 1488:     $thisdisfn=~s/\/+/\//g;
 1489:     my $resdir=
 1490:     $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cudom.'/'.$cuname.'/'.
 1491:       $thisdisfn;
 1492:       $r->print('<h1>Directory <tt>'.$thisdisfn.'</tt></h1>'.
 1493:                 'Target: <tt>'.$resdir.'</tt><br />');
 1494: 
 1495:       my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
 1496: 
 1497:       opendir(DIR,$fn);
 1498:       my @files=sort(readdir(DIR));
 1499:       foreach my $filename (@files) {
 1500:          my ($cdev,$cino,$cmode,$cnlink,
 1501:             $cuid,$cgid,$crdev,$csize,
 1502:             $catime,$cmtime,$cctime,
 1503:             $cblksize,$cblocks)=stat($fn.'/'.$filename);
 1504: 
 1505:          my $extension='';
 1506:          if ($filename=~/\.(\w+)$/) { $extension=$1; }
 1507:          if ($cmode&$dirptr) {
 1508: 	   if (($filename!~/^\./) && ($ENV{'form.pubrec'})) {
 1509: 	      &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
 1510: 	   }
 1511:          } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
 1512:                   ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
 1513: # find out publication status and/or exiting metadata
 1514: 	     my $publishthis=0;
 1515:              if (-e $resdir.'/'.$filename) {
 1516: 	        my ($rdev,$rino,$rmode,$rnlink,
 1517: 	        $ruid,$rgid,$rrdev,$rsize,
 1518: 	        $ratime,$rmtime,$rctime,
 1519: 	        $rblksize,$rblocks)=stat($resdir.'/'.$filename);
 1520: 	        if ($rmtime<$cmtime) {
 1521: # previously published, modified now
 1522: 		    $publishthis=1;
 1523:                 }
 1524: 	     } else {
 1525: # never published
 1526: 		 $publishthis=1;
 1527: 	     }
 1528:              if ($publishthis) {
 1529:                 &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
 1530: 	     } else {
 1531:                  $r->print('<br />Skipping '.$filename.'<br />');
 1532:              }
 1533:              $r->rflush();
 1534:          }
 1535:       }
 1536:       closedir(DIR);
 1537: }
 1538: #########################################
 1539: 
 1540: =pod
 1541: 
 1542: =item B<handler>
 1543: 
 1544: A basic outline of the handler subroutine follows.
 1545: 
 1546: =over 4
 1547: 
 1548: =item *
 1549: 
 1550: Get query string for limited number of parameters.
 1551: 
 1552: =item *
 1553: 
 1554: Check filename.
 1555: 
 1556: =item *
 1557: 
 1558: File is there and owned, init lookup tables.
 1559: 
 1560: =item *
 1561: 
 1562: Start page output.
 1563: 
 1564: =item *
 1565: 
 1566: Evaluate individual file, and then output information.
 1567: 
 1568: =item *
 1569: 
 1570: Publishing from $thisfn to $thistarget with $thisembstyle.
 1571: 
 1572: =back
 1573: 
 1574: =cut
 1575: 
 1576: #########################################
 1577: #########################################
 1578: sub handler {
 1579:   my $r=shift;
 1580: 
 1581:   if ($r->header_only) {
 1582:      $r->content_type('text/html');
 1583:      $r->send_http_header;
 1584:      return OK;
 1585:   }
 1586: 
 1587: # Get query string for limited number of parameters
 1588: 
 1589:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1590:                                             ['filename']);
 1591: 
 1592: # -------------------------------------------------------------- Check filename
 1593: 
 1594:   my $fn=$ENV{'form.filename'};
 1595: 
 1596:   
 1597:   unless ($fn) { 
 1598:      $r->log_reason($cuname.' at '.$cudom.
 1599:          ' trying to publish empty filename', $r->filename); 
 1600:      return HTTP_NOT_FOUND;
 1601:   } 
 1602: 
 1603:   ($cuname,$cudom)=
 1604:     &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
 1605:   unless (($cuname) && ($cudom)) {
 1606:      $r->log_reason($cuname.' at '.$cudom.
 1607:          ' trying to publish file '.$ENV{'form.filename'}.
 1608:          ' ('.$fn.') - not authorized', 
 1609:          $r->filename); 
 1610:      return HTTP_NOT_ACCEPTABLE;
 1611:   }
 1612: 
 1613:   unless (&Apache::lonnet::homeserver($cuname,$cudom) 
 1614:           eq $r->dir_config('lonHostID')) {
 1615:      $r->log_reason($cuname.' at '.$cudom.
 1616:          ' trying to publish file '.$ENV{'form.filename'}.
 1617:          ' ('.$fn.') - not homeserver ('.
 1618:          &Apache::lonnet::homeserver($cuname,$cudom).')', 
 1619:          $r->filename); 
 1620:      return HTTP_NOT_ACCEPTABLE;
 1621:   }
 1622: 
 1623:   $fn=~s/^http\:\/\/[^\/]+//;
 1624:   $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
 1625: 
 1626:   my $targetdir='';
 1627:   $docroot=$r->dir_config('lonDocRoot'); 
 1628:   if ($1 ne $cuname) {
 1629:      $r->log_reason($cuname.' at '.$cudom.
 1630:          ' trying to publish unowned file '.$ENV{'form.filename'}.
 1631:          ' ('.$fn.')', 
 1632:          $r->filename); 
 1633:      return HTTP_NOT_ACCEPTABLE;
 1634:   } else {
 1635:       $targetdir=$docroot.'/res/'.$cudom;
 1636:   }
 1637:                                  
 1638:   
 1639:   unless (-e $fn) { 
 1640:      $r->log_reason($cuname.' at '.$cudom.
 1641:          ' trying to publish non-existing file '.$ENV{'form.filename'}.
 1642:          ' ('.$fn.')', 
 1643:          $r->filename); 
 1644:      return HTTP_NOT_FOUND;
 1645:   } 
 1646: 
 1647: unless ($ENV{'form.phase'} eq 'two') {
 1648: 
 1649: # -------------------------------- File is there and owned, init lookup tables.
 1650: 
 1651:   %addid=();
 1652: 
 1653:   {
 1654:       my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
 1655:       while (<$fh>=~/(\w+)\s+(\w+)/) {
 1656:           $addid{$1}=$2;
 1657:       }
 1658:   }
 1659: 
 1660:   %nokey=();
 1661: 
 1662:   {
 1663:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
 1664:       while (<$fh>) {
 1665:           my $word=$_;
 1666:           chomp($word);
 1667:           $nokey{$word}=1;
 1668:       }
 1669:   }
 1670: 
 1671: }
 1672: 
 1673: # ---------------------------------------------------------- Start page output.
 1674: 
 1675:   $r->content_type('text/html');
 1676:   $r->send_http_header;
 1677: 
 1678:   $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
 1679:   $r->print(&Apache::loncommon::bodytag('Resource Publication'));
 1680: 
 1681: 
 1682:   my $thisfn=$fn;
 1683: 
 1684:   my $thistarget=$thisfn;
 1685:       
 1686:   $thistarget=~s/^\/home/$targetdir/;
 1687:   $thistarget=~s/\/public\_html//;
 1688: 
 1689:   my $thisdistarget=$thistarget;
 1690:   $thisdistarget=~s/^$docroot//;
 1691: 
 1692:   my $thisdisfn=$thisfn;
 1693:   $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
 1694: 
 1695:   if ($fn=~/\/$/) {
 1696: # -------------------------------------------------------- This is a directory
 1697:       &publishdirectory($r,$fn,$thisdisfn);
 1698: 
 1699:   } else {
 1700: # ---------------------- Evaluate individual file, and then output information.
 1701:       $thisfn=~/\.(\w+)$/;
 1702:       my $thistype=$1;
 1703:       my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 1704: 
 1705:       $r->print('<h2>Publishing '.
 1706:         &Apache::loncommon::filedescription($thistype).' <tt>'.
 1707:         '<a href="/~'.$cuname.'/'.$thisdisfn.'" target="cat">'.$thisdisfn.
 1708:         '</a></tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
 1709:    
 1710:       if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
 1711:           $r->print('<h3><font color="red">Co-Author: '.$cuname.' at '.$cudom.
 1712: 		    '</font></h3>');
 1713:       }
 1714: 
 1715:       if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
 1716:           $r->print('<br /><a href="/adm/diff?filename=/~'.$cuname.'/'.
 1717:                     $thisdisfn.
 1718:   	  '&versiontwo=priv" target="cat">Diffs with Current Version</a><p>');
 1719:       }
 1720:   
 1721: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
 1722: 
 1723:        unless ($ENV{'form.phase'} eq 'two') {
 1724:          $r->print(
 1725:           '<hr />'.&publish($thisfn,$thistarget,$thisembstyle));
 1726:        } else {
 1727:            $r->print('<hr />');
 1728:            &phasetwo($r,$thisfn,$thistarget,$thisembstyle,$thisdistarget); 
 1729:        }  
 1730: 
 1731:   }
 1732:   $r->print('</body></html>');
 1733: 
 1734:   return OK;
 1735: }
 1736: 
 1737: 1;
 1738: __END__
 1739: 
 1740: =pod
 1741: 
 1742: =back
 1743: 
 1744: =cut
 1745: 

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