File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.105: download - view: text, annotated - select for diffs
Sun Oct 20 18:39:36 2002 UTC (21 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Toward bug 492 - make metadata parser results available to other modules.

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.105 2002/10/20 18:39:36 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: 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: 
  492:     my $parser=HTML::LCParser->new($content);
  493:     my $token;
  494:     while ($token=$parser->get_token) {
  495: 	if ($token->[0] eq 'S') {
  496: 	    my $counter;
  497: 	    if ($counter=$addid{$token->[1]}) {
  498: 		if ($counter eq 'id') {
  499: 		    if (defined($token->[2]->{'id'})) {
  500: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
  501: 		    } else {
  502: 			$needsfixup=1;
  503: 		    }
  504: 		} else {
  505: 		    if (defined($token->[2]->{'index'})) {
  506: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
  507: 		    } else {
  508: 			$needsfixup=1;
  509: 		    }
  510: 		}
  511: 	    }
  512: 	}
  513:     }
  514:     return ($needsfixup,$maxid,$maxindex);
  515: }
  516: 
  517: #########################################
  518: #########################################
  519: 
  520: =pod
  521: 
  522: =item B<get_all_text_unbalanced>
  523: 
  524: Currently undocumented    
  525: 
  526: =cut
  527: 
  528: #########################################
  529: #########################################
  530: sub get_all_text_unbalanced {
  531:     #there is a copy of this in lonxml.pm
  532:     my($tag,$pars)= @_;
  533:     my $token;
  534:     my $result='';
  535:     $tag='<'.$tag.'>';
  536:     while ($token = $$pars[-1]->get_token) {
  537: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  538: 	    $result.=$token->[1];
  539: 	} elsif ($token->[0] eq 'PI') {
  540: 	    $result.=$token->[2];
  541: 	} elsif ($token->[0] eq 'S') {
  542: 	    $result.=$token->[4];
  543: 	} elsif ($token->[0] eq 'E')  {
  544: 	    $result.=$token->[2];
  545: 	}
  546: 	if ($result =~ /(.*)$tag(.*)/) {
  547: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
  548: 	    #&Apache::lonnet::logthis('Result is :'.$1);
  549: 	    $result=$1;
  550: 	    my $redo=$tag.$2;
  551: 	    push (@$pars,HTML::LCParser->new(\$redo));
  552: 	    $$pars[-1]->xml_mode('1');
  553: 	    last;
  554: 	}
  555:     }
  556:     return $result
  557: }
  558: 
  559: #########################################
  560: #########################################
  561: 
  562: =pod
  563: 
  564: =item B<fix_ids_and_indices>
  565: 
  566: Currently undocumented    
  567: 
  568: =cut
  569: 
  570: #########################################
  571: #########################################
  572: #Arguably this should all be done as a lonnet::ssi instead
  573: sub fix_ids_and_indices {
  574:     my ($logfile,$source,$target)=@_;
  575: 
  576:     my %allow;
  577:     my $content;
  578:     {
  579: 	my $org=Apache::File->new($source);
  580: 	$content=join('',<$org>);
  581:     }
  582: 
  583:     my ($needsfixup,$maxid,$maxindex)=&get_max_ids_indices(\$content);
  584: 
  585:     if ($needsfixup) {
  586: 	print $logfile "Needs ID and/or index fixup\n".
  587: 	    "Max ID   : $maxid (min 10)\n".
  588:                 "Max Index: $maxindex (min 10)\n";
  589:     }
  590:     my $outstring='';
  591:     my @parser;
  592:     $parser[0]=HTML::LCParser->new(\$content);
  593:     $parser[-1]->xml_mode(1);
  594:     my $token;
  595:     while (@parser) {
  596: 	while ($token=$parser[-1]->get_token) {
  597: 	    if ($token->[0] eq 'S') {
  598: 		my $counter;
  599: 		my $tag=$token->[1];
  600: 		my $lctag=lc($tag);
  601: 		if ($lctag eq 'allow') {
  602: 		    $allow{$token->[2]->{'src'}}=1;
  603: 		    next;
  604: 		}
  605: 		my %parms=%{$token->[2]};
  606: 		$counter=$addid{$tag};
  607: 		if (!$counter) { $counter=$addid{$lctag}; }
  608: 		if ($counter) {
  609: 		    if ($counter eq 'id') {
  610: 			unless (defined($parms{'id'})) {
  611: 			    $maxid++;
  612: 			    $parms{'id'}=$maxid;
  613: 			    print $logfile 'ID: '.$tag.':'.$maxid."\n";
  614: 			}
  615: 		    } elsif ($counter eq 'index') {
  616: 			unless (defined($parms{'index'})) {
  617: 			    $maxindex++;
  618: 			    $parms{'index'}=$maxindex;
  619: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
  620: 			}
  621: 		    }
  622: 		}
  623: 		foreach my $type ('src','href','background','bgimg') {
  624: 		    foreach my $key (keys(%parms)) {
  625: 			if ($key =~ /^$type$/i) {
  626: 			    $parms{$key}=&set_allow(\%allow,$logfile,
  627: 						    $target,$tag,
  628: 						    $parms{$key});
  629: 			}
  630: 		    }
  631: 		}
  632: 		# probably a <randomlabel> image type <label>
  633: 		if ($lctag eq 'label' && defined($parms{'description'})) {
  634: 		    my $next_token=$parser[-1]->get_token();
  635: 		    if ($next_token->[0] eq 'T') {
  636: 			$next_token->[1]=&set_allow(\%allow,$logfile,
  637: 						    $target,$tag,
  638: 						    $next_token->[1]);
  639: 		    }
  640: 		    $parser[-1]->unget_token($next_token);
  641: 		}
  642: 		if ($lctag eq 'applet') {
  643: 		    my $codebase='';
  644: 		    if (defined($parms{'codebase'})) {
  645: 			my $oldcodebase=$parms{'codebase'};
  646: 			unless ($oldcodebase=~/\/$/) {
  647: 			    $oldcodebase.='/';
  648: 			}
  649: 			$codebase=&urlfixup($oldcodebase,$target);
  650: 			$codebase=~s/\/$//;    
  651: 			if ($codebase ne $oldcodebase) {
  652: 			    $parms{'codebase'}=$codebase;
  653: 			    print $logfile 'URL codebase: '.$tag.':'.
  654: 				$oldcodebase.' - '.
  655: 				    $codebase."\n";
  656: 			}
  657: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
  658: 		    } else {
  659: 			foreach ('archive','code','object') {
  660: 			    if (defined($parms{$_})) {
  661: 				my $oldurl=$parms{$_};
  662: 				my $newurl=&urlfixup($oldurl,$target);
  663: 				$newurl=~s/\/[^\/]+$/\/\*/;
  664: 				print $logfile 'Allow: applet '.$_.':'.
  665: 				    $oldurl.' allows '.
  666: 					$newurl."\n";
  667: 				$allow{&absoluteurl($newurl,$target)}=1;
  668: 			    }
  669: 			}
  670: 		    }
  671: 		}
  672: 		my $newparmstring='';
  673: 		my $endtag='';
  674: 		foreach (keys %parms) {
  675: 		    if ($_ eq '/') {
  676: 			$endtag=' /';
  677: 		    } else { 
  678: 			my $quote=($parms{$_}=~/\"/?"'":'"');
  679: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
  680: 		    }
  681: 		}
  682: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  683: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
  684: 		if ($lctag eq 'm') {
  685: 		    $outstring.=&get_all_text_unbalanced('/m',\@parser);
  686: 		}
  687: 	    } elsif ($token->[0] eq 'E') {
  688: 		if ($token->[2]) {
  689: 		    unless ($token->[1] eq 'allow') {
  690: 			$outstring.='</'.$token->[1].'>';
  691: 		    }
  692: 		}
  693: 	    } else {
  694: 		$outstring.=$token->[1];
  695: 	    }
  696: 	}
  697: 	pop(@parser);
  698:     }
  699: 
  700:     if ($needsfixup) {
  701: 	print $logfile "End of ID and/or index fixup\n".
  702: 	    "Max ID   : $maxid (min 10)\n".
  703: 		"Max Index: $maxindex (min 10)\n";
  704:     } else {
  705: 	print $logfile "Does not need ID and/or index fixup\n";
  706:     }
  707: 
  708:     return ($outstring,%allow);
  709: }
  710: 
  711: #########################################
  712: #########################################
  713: 
  714: =pod
  715: 
  716: =item B<store_metadata>
  717: 
  718: Store the metadata in the metadata table in the loncapa database.
  719: Uses lonmysql to access the database.
  720: 
  721: Inputs: \%metadata
  722: 
  723: Returns: (error,status).  error is undef on success, status is undef on error.
  724: 
  725: =cut
  726: 
  727: #########################################
  728: #########################################
  729: sub store_metadata {
  730:     my %metadata = %{shift()};
  731:     my $error;
  732:     # Determine if the table exists
  733:     my $status = &Apache::lonmysql::check_table('metadata');
  734:     if (! defined($status)) {
  735:         $error='<font color="red">WARNING: Cannot connect to '.
  736:             'database!</font>';
  737:         &Apache::lonnet::logthis($error);
  738:         return ($error,undef);
  739:     }
  740:     if ($status == 0) {
  741:         # It would be nice to actually create the table....
  742:         $error ='<font color="red">WARNING: The metadata table does not '.
  743:             'exist in the LON-CAPA database.</font>';
  744:         &Apache::lonnet::logthis($error);
  745:         return ($error,undef);
  746:     }
  747:     # Remove old value from table
  748:     $status = &Apache::lonmysql::remove_from_table
  749:         ('metadata','url',$metadata{'url'});
  750:     if (! defined($status)) {
  751:         $error = '<font color="red">Error when removing old values from '.
  752:             'metadata table in LON-CAPA database.</font>';
  753:         &Apache::lonnet::logthis($error);
  754:         return ($error,undef);
  755:     }
  756:     # Store data in table.
  757:     $status = &Apache::lonmysql::store_row('metadata',\%metadata);
  758:     if (! defined($status)) {
  759:         $error='<font color="red">Error occured storing new values in '.
  760:             'metadata table in LON-CAPA database</font>';
  761:         &Apache::lonnet::logthis($error);
  762:         return ($error,undef);
  763:     }
  764:     return (undef,$status);
  765: }
  766: 
  767: #########################################
  768: #########################################
  769: 
  770: =pod
  771: 
  772: =item B<publish>
  773: 
  774: This is the workhorse function of this module.  This subroutine generates
  775: backup copies, performs any automatic processing (prior to publication,
  776: especially for rat and ssi files),
  777: 
  778: I<Additional documentation needed.>
  779: 
  780: =cut
  781: 
  782: #########################################
  783: #########################################
  784: sub publish {
  785: 
  786:     my ($source,$target,$style,$batch)=@_;
  787:     my $logfile;
  788:     my $scrout='';
  789:     my $allmeta='';
  790:     my $content='';
  791:     my %allow=();
  792: 
  793:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  794: 	return 
  795:          '<font color=red>No write permission to user directory, FAIL</font>';
  796:     }
  797:     print $logfile 
  798: "\n\n================= Publish ".localtime()." Phase One  ================\n";
  799: 
  800:     if (($style eq 'ssi') || ($style eq 'rat')) {
  801: # ------------------------------------------------------- This needs processing
  802: 
  803: # ----------------------------------------------------------------- Backup Copy
  804: 	my $copyfile=$source.'.save';
  805:         if (copy($source,$copyfile)) {
  806: 	    print $logfile "Copied original file to ".$copyfile."\n";
  807:         } else {
  808: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
  809:           return "<font color=red>Failed to write backup copy, $!,FAIL</font>";
  810:         }
  811: # ------------------------------------------------------------- IDs and indices
  812: 	
  813: 	my $outstring;
  814: 	($outstring,%allow)=&fix_ids_and_indices($logfile,$source,$target);
  815: # ------------------------------------------------------------ Construct Allows
  816:     
  817: 	$scrout.='<h3>Dependencies</h3>';
  818:         my $allowstr='';
  819:         foreach (sort(keys(%allow))) {
  820: 	   my $thisdep=$_;
  821: 	   if ($thisdep !~ /[^\s]/) { next; }
  822:            unless ($style eq 'rat') { 
  823:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
  824: 	   }
  825:            $scrout.='<br>';
  826:            unless ($thisdep=~/\*/) {
  827: 	       $scrout.='<a href="'.$thisdep.'">';
  828:            }
  829:            $scrout.='<tt>'.$thisdep.'</tt>';
  830:            unless ($thisdep=~/\*/) {
  831: 	       $scrout.='</a>';
  832:                if (
  833:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
  834:                                             $thisdep.'.meta') eq '-1') {
  835: 		   $scrout.= ' - <font color="red">Currently not available'.
  836: 		       '</font>';
  837:                } else {
  838:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
  839:                              &Apache::lonnet::declutter($thisdep).'___usage'
  840:                                  => time);
  841:                    $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
  842:                    if ((defined($1)) && (defined($2))) {
  843:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
  844: 					   $1,$2);
  845: 		   }
  846: 	       }
  847:            }
  848:         }
  849:         $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
  850: 
  851: 	#Encode any High ASCII characters
  852: 	$outstring=&HTML::Entities::encode($outstring,"\200-\377");
  853: # ------------------------------------------------------------- Write modified.
  854: 
  855:         {
  856:           my $org;
  857:           unless ($org=Apache::File->new('>'.$source)) {
  858:              print $logfile "No write permit to $source\n";
  859:              return 
  860: 		 '<font color="red">No write permission to '.$source.
  861: 		 ', FAIL</font>';
  862: 	  }
  863:           print($org $outstring);
  864:         }
  865: 	  $content=$outstring;
  866: 
  867:     }
  868: # -------------------------------------------- Initial step done, now metadata.
  869: 
  870: # --------------------------------------- Storage for metadata keys and fields.
  871: 
  872:      %metadatafields=();
  873:      %metadatakeys=();
  874:      
  875:      my %oldparmstores=();
  876:      
  877:     unless ($batch) {
  878:      $scrout.='<h3>Metadata Information ' .
  879:        Apache::loncommon::help_open_topic("Metadata_Description")
  880:        . '</h3>';
  881:     }
  882: 
  883: # ------------------------------------------------ First, check out environment
  884:      unless (-e $source.'.meta') {
  885:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
  886: 	                          $ENV{'environment.middlename'}.' '.
  887: 		                  $ENV{'environment.lastname'}.' '.
  888: 		                  $ENV{'environment.generation'};
  889:         $metadatafields{'author'}=~s/\s+/ /g;
  890:         $metadatafields{'author'}=~s/\s+$//;
  891:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
  892: 
  893: # ------------------------------------------------ Check out directory hierachy
  894: 
  895:         my $thisdisfn=$source;
  896:         $thisdisfn=~s/^\/home\/$cuname\///;
  897: 
  898:         my @urlparts=split(/\//,$thisdisfn);
  899:         $#urlparts--;
  900: 
  901:         my $currentpath='/home/'.$cuname.'/';
  902: 
  903:         foreach (@urlparts) {
  904: 	    $currentpath.=$_.'/';
  905:             $scrout.=&metaread($logfile,$currentpath.'default.meta');
  906:         }
  907: 
  908: # ------------------- Clear out parameters and stores (there should not be any)
  909: 
  910:         foreach (keys %metadatafields) {
  911: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  912: 		delete $metadatafields{$_};
  913:             }
  914:         }
  915: 
  916:     } else {
  917: # ---------------------- Read previous metafile, remember parameters and stores
  918: 
  919:         $scrout.=&metaread($logfile,$source.'.meta');
  920: 
  921:         foreach (keys %metadatafields) {
  922: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  923:                 $oldparmstores{$_}=1;
  924: 		delete $metadatafields{$_};
  925:             }
  926:         }
  927:         
  928:     }
  929: 
  930: # -------------------------------------------------- Parse content for metadata
  931:     if ($style eq 'ssi') {
  932:         my $oldenv=$ENV{'request.uri'};
  933: 
  934:         $ENV{'request.uri'}=$target;
  935:         $allmeta=Apache::lonxml::xmlparse(undef,'meta',$content);
  936:         $ENV{'request.uri'}=$oldenv;
  937: 
  938:         &metaeval($allmeta);
  939:     }
  940: # ---------------- Find and document discrepancies in the parameters and stores
  941: 
  942:         my $chparms='';
  943:         foreach (sort keys %metadatafields) {
  944: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  945:                 unless ($_=~/\.\w+$/) { 
  946:                    unless ($oldparmstores{$_}) {
  947: 		      print $logfile 'New: '.$_."\n";
  948:                       $chparms.=$_.' ';
  949:                    }
  950: 	        }
  951:             }
  952:         }
  953:         if ($chparms) {
  954: 	    $scrout.='<p><b>New parameters or stored values:</b> '.
  955:                      $chparms;
  956:         }
  957: 
  958:         $chparms='';
  959:         foreach (sort keys %oldparmstores) {
  960: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  961:                 unless (($metadatafields{$_.'.name'}) ||
  962:                         ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
  963: 		    print $logfile 'Obsolete: '.$_."\n";
  964:                     $chparms.=$_.' ';
  965:                 }
  966:             }
  967:         }
  968:         if ($chparms) {
  969: 	    $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
  970:                      $chparms;
  971:         }
  972: 
  973: # ------------------------------------------------------- Now have all metadata
  974: 
  975:         my %keywords=();
  976:         
  977: 	if (length($content)<500000) {
  978: 	    my $textonly=$content;
  979:             $textonly=~s/\<script[^\<]+\<\/script\>//g;
  980:             $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
  981:             $textonly=~s/\<[^\>]*\>//g;
  982:             $textonly=~tr/A-Z/a-z/;
  983:             $textonly=~s/[\$\&][a-z]\w*//g;
  984:             $textonly=~s/[^a-z\s]//g;
  985: 
  986:             foreach ($textonly=~m/(\w+)/g) {
  987: 		unless ($nokey{$_}) {
  988:                    $keywords{$_}=1;
  989:                 } 
  990:             }
  991:         }
  992: 
  993:             
  994:             foreach (split(/\W+/,$metadatafields{'keywords'})) {
  995: 		$keywords{$_}=1;
  996:             }
  997: # --------------------------------------------------- Now we also have keywords
  998: # =============================================================================
  999: # INTERACTIVE MODE
 1000: #
 1001:    unless ($batch) {
 1002:         $scrout.=
 1003:      '<form name="pubform" action="/adm/publish" method="post">'.
 1004:        '<p><input type="submit" value="Finalize Publication" /></p>'.
 1005:           &hiddenfield('phase','two').
 1006:           &hiddenfield('filename',$ENV{'form.filename'}).
 1007: 	  &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
 1008:           &hiddenfield('dependencies',join(',',keys %allow)).
 1009:           &textfield('Title','title',$metadatafields{'title'}).
 1010:           &textfield('Author(s)','author',$metadatafields{'author'}).
 1011: 	  &textfield('Subject','subject',$metadatafields{'subject'});
 1012: 
 1013: # --------------------------------------------------- Scan content for keywords
 1014: 
 1015:         my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
 1016: 	my $keywordout=<<"END";
 1017: <script>
 1018: function checkAll(field)
 1019: {
 1020:     for (i = 0; i < field.length; i++)
 1021:         field[i].checked = true ;
 1022: }
 1023: 
 1024: function uncheckAll(field)
 1025: {
 1026:     for (i = 0; i < field.length; i++)
 1027:         field[i].checked = false ;
 1028: }
 1029: </script>
 1030: <p><b>Keywords: $keywords_help</b> 
 1031: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)"> 
 1032: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)"> 
 1033: <br />
 1034: END
 1035:         $keywordout.='<table border=2><tr>';
 1036:         my $colcount=0;
 1037: 
 1038:             foreach (sort keys %keywords) {
 1039:                 $keywordout.='<td><input type=checkbox name="keywords" value="'.$_.'"';
 1040:                 if ($metadatafields{'keywords'}) {
 1041:                    if ($metadatafields{'keywords'}=~/$_/) { 
 1042:                       $keywordout.=' checked'; 
 1043:                    }
 1044: 	        } elsif (&Apache::loncommon::keyword($_)) {
 1045: 	            $keywordout.=' checked';
 1046:                 } 
 1047:                 $keywordout.='>'.$_.'</td>';
 1048:                 if ($colcount>10) {
 1049: 		    $keywordout.="</tr><tr>\n";
 1050:                     $colcount=0;
 1051:                 }
 1052:                 $colcount++;
 1053:             }
 1054:         
 1055: 	$keywordout.='</tr></table>';
 1056: 
 1057:         $scrout.=$keywordout;
 1058: 
 1059:         $scrout.=&textfield('Additional Keywords','addkey','');
 1060: 
 1061:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
 1062: 
 1063:         $scrout.=
 1064:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
 1065:               $metadatafields{'abstract'}.'</textarea>';
 1066: 
 1067: 	$source=~/\.(\w+)$/;
 1068: 
 1069: 	$scrout.=&hiddenfield('mime',$1);
 1070: 
 1071:         $scrout.=&selectbox('Language','language',
 1072:                             $metadatafields{'language'},
 1073: 			    \&Apache::loncommon::languagedescription,
 1074: 			    (&Apache::loncommon::languageids),
 1075: 			     );
 1076: 
 1077:         unless ($metadatafields{'creationdate'}) {
 1078: 	    $metadatafields{'creationdate'}=time;
 1079:         }
 1080:         $scrout.=&hiddenfield('creationdate',
 1081:               &Apache::loncommon::unsqltime($metadatafields{'creationdate'}));
 1082: 
 1083:         $scrout.=&hiddenfield('lastrevisiondate',time);
 1084: 
 1085: 			   
 1086: 	$scrout.=&textfield('Publisher/Owner','owner',
 1087:                             $metadatafields{'owner'});
 1088: 
 1089: # -------------------------------------------------- Correct copyright for rat.
 1090:     if ($style eq 'rat') {
 1091: 	if ($metadatafields{'copyright'} eq 'public') { 
 1092: 	    delete $metadatafields{'copyright'};
 1093: 	}
 1094:         $scrout.=&selectbox('Copyright/Distribution','copyright',
 1095:                             $metadatafields{'copyright'},
 1096: 			    \&Apache::loncommon::copyrightdescription,
 1097: 		     (grep !/^public$/,(&Apache::loncommon::copyrightids)));
 1098:     }
 1099:     else {
 1100:         $scrout.=&selectbox('Copyright/Distribution','copyright',
 1101:                             $metadatafields{'copyright'},
 1102: 			    \&Apache::loncommon::copyrightdescription,
 1103: 			     (&Apache::loncommon::copyrightids));
 1104:     }
 1105: 
 1106:     my $copyright_help =
 1107:         Apache::loncommon::help_open_topic('Publishing_Copyright');
 1108:     $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
 1109:     return $scrout.
 1110:         '<p><input type="submit" value="Finalize Publication" /></p></form>';
 1111: # =============================================================================
 1112: # BATCH MODE
 1113: #
 1114:   } else {
 1115: # Transfer metadata directly to environment for stage 2
 1116:     foreach (keys %metadatafields) {
 1117: 	$ENV{'form.'.$_}=$metadatafields{$_};
 1118:     }
 1119:     $ENV{'form.addkey'}='';
 1120:     $ENV{'form.keywords'}='';
 1121:     foreach (keys %keywords) {
 1122:         if ($metadatafields{'keywords'}) {
 1123:            if ($metadatafields{'keywords'}=~/$_/) { 
 1124:               $ENV{'form.keywords'}.=$_.','; 
 1125:            }
 1126: 	} elsif (&Apache::loncommon::keyword($_)) {
 1127: 	    $ENV{'form.keywords'}.=$_.',';
 1128:         } 
 1129:     }
 1130:     $ENV{'form.keywords'}=~s/\,$//;
 1131:     unless ($ENV{'form.creationdate'}) { $ENV{'form.creationdate'}=time; }
 1132:     $ENV{'form.lastrevisiondate'}=time;
 1133:     if ((($style eq 'rat') && ($ENV{'form.copyright'} eq 'public')) ||
 1134:         (!$ENV{'form.copyright'})) { 
 1135: 	$ENV{'form.copyright'}='default';
 1136:     } 
 1137:     $ENV{'form.allmeta'}=&Apache::lonnet::escape($allmeta);
 1138:     return $scrout;
 1139:   }
 1140: }
 1141: 
 1142: #########################################
 1143: #########################################
 1144: 
 1145: =pod 
 1146: 
 1147: =item B<phasetwo>
 1148: 
 1149: Render second interface showing status of publication steps.
 1150: This is publication step two.
 1151: 
 1152: Parameters:
 1153: 
 1154: =over 4
 1155: 
 1156: =item I<$source>
 1157: 
 1158: =item I<$target>
 1159: 
 1160: =item I<$style>
 1161: 
 1162: =item I<$distarget>
 1163: 
 1164: =back
 1165: 
 1166: Returns:
 1167: 
 1168: =over 4
 1169: 
 1170: =item Scalar string
 1171: 
 1172: String contains status (errors and warnings) and information associated with
 1173: the server's attempts at publication.     
 1174: 
 1175: =cut
 1176: 
 1177: #'stupid emacs
 1178: #########################################
 1179: #########################################
 1180: sub phasetwo {
 1181: 
 1182:     my ($r,$source,$target,$style,$distarget,$batch)=@_;
 1183:     $source=~s/\/+/\//g;
 1184:     $target=~s/\/+/\//g;
 1185:     $distarget=~s/\/+/\//g;
 1186:     my $logfile;
 1187:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
 1188: 	return 
 1189:             '<font color=red>No write permission to user directory, FAIL</font>';
 1190:     }
 1191:     print $logfile 
 1192:         "\n================= Publish ".localtime()." Phase Two  ================\n";
 1193:     
 1194:     %metadatafields=();
 1195:     %metadatakeys=();
 1196:     
 1197:     &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
 1198:     
 1199:     $metadatafields{'title'}=$ENV{'form.title'};
 1200:     $metadatafields{'author'}=$ENV{'form.author'};
 1201:     $metadatafields{'subject'}=$ENV{'form.subject'};
 1202:     $metadatafields{'notes'}=$ENV{'form.notes'};
 1203:     $metadatafields{'abstract'}=$ENV{'form.abstract'};
 1204:     $metadatafields{'mime'}=$ENV{'form.mime'};
 1205:     $metadatafields{'language'}=$ENV{'form.language'};
 1206:     $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
 1207:     $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
 1208:     $metadatafields{'owner'}=$ENV{'form.owner'};
 1209:     $metadatafields{'copyright'}=$ENV{'form.copyright'};
 1210:     $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
 1211:     
 1212:     my $allkeywords=$ENV{'form.addkey'};
 1213:     if (exists($ENV{'form.keywords'})) {
 1214:         if (ref($ENV{'form.keywords'})) {
 1215:             $allkeywords .= ','.join(',',@{$ENV{'form.keywords'}});
 1216:         } else {
 1217:             $allkeywords .= ','.$ENV{'form.keywords'};
 1218:         }
 1219:     }
 1220:     $allkeywords=~s/\W+/\,/;
 1221:     $allkeywords=~s/^\,//;
 1222:     $metadatafields{'keywords'}=$allkeywords;
 1223:     
 1224:     {
 1225:         print $logfile "\nWrite metadata file for ".$source;
 1226:         my $mfh;
 1227:         unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
 1228:             return 
 1229:                 '<font color=red>Could not write metadata, FAIL</font>';
 1230:         }
 1231:         foreach (sort keys %metadatafields) {
 1232:             unless ($_=~/\./) {
 1233:                 my $unikey=$_;
 1234:                 $unikey=~/^([A-Za-z]+)/;
 1235:                 my $tag=$1;
 1236:                 $tag=~tr/A-Z/a-z/;
 1237:                 print $mfh "\n\<$tag";
 1238:                 foreach (split(/\,/,$metadatakeys{$unikey})) {
 1239:                     my $value=$metadatafields{$unikey.'.'.$_};
 1240:                     $value=~s/\"/\'\'/g;
 1241:                     print $mfh ' '.$_.'="'.$value.'"';
 1242:                 }
 1243:                 print $mfh '>'.
 1244:                     &HTML::Entities::encode($metadatafields{$unikey})
 1245:                         .'</'.$tag.'>';
 1246:             }
 1247:         }
 1248:         $r->print('<p>Wrote Metadata');
 1249:         print $logfile "\nWrote metadata";
 1250:     }
 1251:     
 1252: # -------------------------------- Synchronize entry with SQL metadata database
 1253: 
 1254:     $metadatafields{'url'} = $distarget;
 1255:     $metadatafields{'version'} = 'current';
 1256:     unless ($metadatafields{'copyright'} eq 'priv') {
 1257:         my ($error,$success) = &store_metadata(\%metadatafields);
 1258:         if ($success) {
 1259:             $r->print('<p>Synchronized SQL metadata database');
 1260:             print $logfile "\nSynchronized SQL metadata database";
 1261:         } else {
 1262:             $r->print($error);
 1263:             print $logfile "\n".$error;
 1264:         }
 1265:     } else {
 1266:         $r->print('<p>Private Publication - did not synchronize database');
 1267:         print $logfile "\nPrivate: Did not synchronize data into ".
 1268:             "SQL metadata database";
 1269:     }
 1270: # ----------------------------------------------------------- Copy old versions
 1271:    
 1272:     if (-e $target) {
 1273:         my $filename;
 1274:         my $maxversion=0;
 1275:         $target=~/(.*)\/([^\/]+)\.(\w+)$/;
 1276:         my $srcf=$2;
 1277:         my $srct=$3;
 1278:         my $srcd=$1;
 1279:         unless ($srcd=~/^\/home\/httpd\/html\/res/) {
 1280:             print $logfile "\nPANIC: Target dir is ".$srcd;
 1281:             return "<font color=red>Invalid target directory, FAIL</font>";
 1282:         }
 1283:         opendir(DIR,$srcd);
 1284:         while ($filename=readdir(DIR)) {
 1285:             if (-l $srcd.'/'.$filename) {
 1286:                 unlink($srcd.'/'.$filename);
 1287:                 unlink($srcd.'/'.$filename.'.meta');
 1288:             } else {
 1289:                 if ($filename=~/$srcf\.(\d+)\.$srct$/) {
 1290:                     $maxversion=($1>$maxversion)?$1:$maxversion;
 1291:                 }
 1292:             }
 1293:         }
 1294:         closedir(DIR);
 1295:         $maxversion++;
 1296:         $r->print('<p>Creating old version '.$maxversion);
 1297:         print $logfile "\nCreating old version ".$maxversion;
 1298:         
 1299:         my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
 1300:         
 1301:         if (copy($target,$copyfile)) {
 1302: 	    print $logfile "Copied old target to ".$copyfile."\n";
 1303:             $r->print('<p>Copied old target file');
 1304:         } else {
 1305: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 1306:             return "<font color=red>Failed to copy old target, $!, FAIL</font>";
 1307:         }
 1308:         
 1309: # --------------------------------------------------------------- Copy Metadata
 1310: 
 1311: 	$copyfile=$copyfile.'.meta';
 1312:         
 1313:         if (copy($target.'.meta',$copyfile)) {
 1314: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
 1315:             $r->print('<p>Copied old metadata')
 1316:         } else {
 1317: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 1318:             if (-e $target.'.meta') {
 1319:                 return 
 1320:                     "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
 1321: 	    }
 1322:         }
 1323:         
 1324:         
 1325:     } else {
 1326:         $r->print('<p>Initial version');
 1327:         print $logfile "\nInitial version";
 1328:     }
 1329: 
 1330: # ---------------------------------------------------------------- Write Source
 1331:     my $copyfile=$target;
 1332:     
 1333:     my @parts=split(/\//,$copyfile);
 1334:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1335:     
 1336:     my $count;
 1337:     for ($count=5;$count<$#parts;$count++) {
 1338:         $path.="/$parts[$count]";
 1339:         if ((-e $path)!=1) {
 1340:             print $logfile "\nCreating directory ".$path;
 1341:             $r->print('<p>Created directory '.$parts[$count]);
 1342:             mkdir($path,0777);
 1343:         }
 1344:     }
 1345:     
 1346:     if (copy($source,$copyfile)) {
 1347:         print $logfile "\nCopied original source to ".$copyfile."\n";
 1348:         $r->print('<p>Copied source file');
 1349:     } else {
 1350:         print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 1351:         return "<font color=red>Failed to copy source, $!, FAIL</font>";
 1352:     }
 1353:     
 1354: # --------------------------------------------------------------- Copy Metadata
 1355: 
 1356:     $copyfile=$copyfile.'.meta';
 1357:     
 1358:     if (copy($source.'.meta',$copyfile)) {
 1359:         print $logfile "\nCopied original metadata to ".$copyfile."\n";
 1360:         $r->print('<p>Copied metadata');
 1361:     } else {
 1362:         print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
 1363:         return 
 1364:             "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
 1365:     }
 1366:     $r->rflush;
 1367: # --------------------------------------------------- Send update notifications
 1368: 
 1369:     my @subscribed=&get_subscribed_hosts($target);
 1370:     foreach my $subhost (@subscribed) {
 1371: 	$r->print('<p>Notifying host '.$subhost.':');$r->rflush;
 1372: 	print $logfile "\nNotifying host ".$subhost.':';
 1373: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 1374: 	$r->print($reply.'<br />');$r->rflush;
 1375: 	print $logfile $reply;
 1376:     }
 1377:     
 1378: # ---------------------------------------- Send update notifications, meta only
 1379: 
 1380:     my @subscribedmeta=&get_subscribed_hosts("$target.meta");
 1381:     foreach my $subhost (@subscribedmeta) {
 1382: 	$r->print('<p>Notifying host for metadata only '.$subhost.':');$r->rflush;
 1383: 	print $logfile "\nNotifying host for metadata only ".$subhost.':';
 1384: 	my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 1385: 					    $subhost);
 1386: 	$r->print($reply.'<br />');$r->rflush;
 1387: 	print $logfile $reply;
 1388:     }
 1389:     
 1390: # --------------------------------------------------- Notify subscribed courses
 1391:     my %courses=&coursedependencies($target);
 1392:     my $now=time;
 1393:     foreach (keys %courses) {
 1394: 	$r->print('<p>Notifying course '.$_.':');$r->rflush;
 1395: 	print $logfile "\nNotifying host ".$_.':';
 1396:         my ($cdom,$cname)=split(/\_/,$_);
 1397: 	my $reply=&Apache::lonnet::cput
 1398:                   ('versionupdate',{$target => $now},$cdom,$cname);
 1399: 	$r->print($reply.'<br />');$r->rflush;
 1400: 	print $logfile $reply;
 1401:     }
 1402: # ------------------------------------------------ Provide link to new resource
 1403:     unless ($batch) {
 1404:         my $thisdistarget=$target;
 1405:         $thisdistarget=~s/^$docroot//;
 1406:         
 1407:         my $thissrc=$source;
 1408:         $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
 1409:         
 1410:         my $thissrcdir=$thissrc;
 1411:         $thissrcdir=~s/\/[^\/]+$/\//;
 1412:         
 1413:         
 1414:         $r->print(
 1415:            '<hr><a href="'.$thisdistarget.'"><font size="+2">'.
 1416:            'View Published Version</font></a>'.
 1417:            '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
 1418:            '<p><a href="'.$thissrcdir.
 1419:                    '"><font size="+2">Back to Source Directory</font></a>');
 1420:     }
 1421: }
 1422: 
 1423: #########################################
 1424: 
 1425: sub batchpublish {
 1426:     my ($r,$srcfile,$targetfile)=@_;
 1427:     $srcfile=~s/\/+/\//g;
 1428:     $targetfile=~s/\/+/\//g;
 1429:     my $thisdisfn=$srcfile;
 1430:     $thisdisfn=~s/\/home\/korte\/public_html\///;
 1431:     $srcfile=~s/\/+/\//g;
 1432: 
 1433:     my $docroot=$r->dir_config('lonDocRoot');
 1434:     my $thisdistarget=$targetfile;
 1435:     $thisdistarget=~s/^$docroot//;
 1436: 
 1437: 
 1438:     undef %metadatafields;
 1439:     undef %metadatakeys;
 1440:      %metadatafields=();
 1441:      %metadatakeys=();
 1442:       $srcfile=~/\.(\w+)$/;
 1443:       my $thistype=$1;
 1444: 
 1445: 
 1446:       my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 1447:      
 1448:     $r->print('<h2>Publishing <tt>'.$thisdisfn.'</tt></h2>');
 1449: 
 1450: # phase one takes
 1451: #  my ($source,$target,$style,$batch)=@_;
 1452:     $r->print('<p>'.&publish($srcfile,$targetfile,$thisembstyle,1).'</p>');
 1453: # phase two takes
 1454: # my ($source,$target,$style,$distarget,batch)=@_;
 1455: # $ENV{'form.allmeta'},$ENV{'form.title'},$ENV{'form.author'},...
 1456:     $r->print('<p>');
 1457:     &phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
 1458:     $r->print('</p>');
 1459:     return '';
 1460: }
 1461: 
 1462: #########################################
 1463: 
 1464: sub publishdirectory {
 1465:     my ($r,$fn,$thisdisfn)=@_;
 1466:     $fn=~s/\/+/\//g;
 1467:     $thisdisfn=~s/\/+/\//g;
 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: 
 1660: 
 1661:   my $thisfn=$fn;
 1662: 
 1663:   my $thistarget=$thisfn;
 1664:       
 1665:   $thistarget=~s/^\/home/$targetdir/;
 1666:   $thistarget=~s/\/public\_html//;
 1667: 
 1668:   my $thisdistarget=$thistarget;
 1669:   $thisdistarget=~s/^$docroot//;
 1670: 
 1671:   my $thisdisfn=$thisfn;
 1672:   $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
 1673: 
 1674:   if ($fn=~/\/$/) {
 1675: # -------------------------------------------------------- This is a directory
 1676:       &publishdirectory($r,$fn,$thisdisfn);
 1677: 
 1678:   } else {
 1679: # ---------------------- Evaluate individual file, and then output information.
 1680:       $thisfn=~/\.(\w+)$/;
 1681:       my $thistype=$1;
 1682:       my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 1683: 
 1684:       $r->print('<h2>Publishing '.
 1685:         &Apache::loncommon::filedescription($thistype).' <tt>'.
 1686:         '<a href="/~'.$cuname.'/'.$thisdisfn.'" target="cat">'.$thisdisfn.
 1687:         '</a></tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
 1688:    
 1689:       if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
 1690:           $r->print('<h3><font color="red">Co-Author: '.$cuname.' at '.$cudom.
 1691: 		    '</font></h3>');
 1692:       }
 1693: 
 1694:       if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
 1695:           $r->print('<br /><a href="/adm/diff?filename=/~'.$cuname.'/'.
 1696:                     $thisdisfn.
 1697:   	  '&versiontwo=priv" target="cat">Diffs with Current Version</a><p>');
 1698:       }
 1699:   
 1700: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
 1701: 
 1702:        unless ($ENV{'form.phase'} eq 'two') {
 1703:          $r->print(
 1704:           '<hr />'.&publish($thisfn,$thistarget,$thisembstyle));
 1705:        } else {
 1706:            $r->print('<hr />');
 1707:            &phasetwo($r,$thisfn,$thistarget,$thisembstyle,$thisdistarget); 
 1708:        }  
 1709: 
 1710:   }
 1711:   $r->print('</body></html>');
 1712: 
 1713:   return OK;
 1714: }
 1715: 
 1716: 1;
 1717: __END__
 1718: 
 1719: =pod
 1720: 
 1721: =back
 1722: 
 1723: =cut
 1724: 

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