File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.103: download - view: text, annotated - select for diffs
Fri Oct 18 13:49:49 2002 UTC (21 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Toward bug 839

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

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