File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.108: download - view: text, annotated - select for diffs
Mon Feb 3 18:03:53 2003 UTC (21 years, 3 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
best wishes to all.

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

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