File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.102: download - view: text, annotated - select for diffs
Thu Oct 10 15:05:36 2002 UTC (21 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
With recent changes this had lots of double slashes - looks ugly and confusing

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

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