File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.126.2.1: download - view: text, annotated - select for diffs
Thu Aug 21 17:12:32 2003 UTC (20 years, 10 months ago) by albertel
Branches: version_1_0_1
Diff to branchpoint 1.126: preferred, unified
- backport 1.130 1.131

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

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