File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.97: download - view: text, annotated - select for diffs
Wed Sep 18 15:43:06 2002 UTC (21 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Still has problems with picking up keywords.

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

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