File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.92: download - view: text, annotated - select for diffs
Fri Aug 9 19:49:30 2002 UTC (21 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixes bug#257, moved resevaldata.db to nohist_resevaldata.db, and deletes hist file

- After installing these diffs you need to do a make install before restarting the webserver

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.92 2002/08/09 19:49:30 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: # 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: lonpublisher takes the proper steps to add resources to the LON-CAPA
   77: digital library.  This includes updating the metadata table in the
   78: LON-CAPA database.
   79: 
   80: =head1 Description
   81: 
   82: lonpublisher is many things to many people.  
   83: To all people it is woefully documented.  
   84: This documentation conforms to this standard.
   85: 
   86: This module publishes a file.  This involves gathering metadata,
   87: versioning the file, copying file from construction space to
   88: publication space, and copying metadata from construction space
   89: to publication space.
   90: 
   91: =head2 Internal Functions
   92: 
   93: =over 4
   94: 
   95: =cut
   96: 
   97: ######################################################################
   98: ######################################################################
   99: 
  100: 
  101: package Apache::lonpublisher;
  102: 
  103: # ------------------------------------------------- modules used by this module
  104: use strict;
  105: use Apache::File;
  106: use File::Copy;
  107: use Apache::Constants qw(:common :http :methods);
  108: use HTML::LCParser;
  109: use Apache::lonxml;
  110: use Apache::lonhomework;
  111: use Apache::loncacc;
  112: use DBI;
  113: use Apache::lonnet();
  114: use Apache::loncommon();
  115: use Apache::lonmysql;
  116: 
  117: my %addid;
  118: my %nokey;
  119: 
  120: my %metadatafields;
  121: my %metadatakeys;
  122: 
  123: my $docroot;
  124: 
  125: my $cuname;
  126: my $cudom;
  127: 
  128: #########################################
  129: #########################################
  130: 
  131: =pod
  132: 
  133: =item metaeval
  134: 
  135: Evaluate string with metadata
  136: 
  137: =cut
  138: 
  139: #########################################
  140: #########################################
  141: sub metaeval {
  142:     my $metastring=shift;
  143:    
  144:         my $parser=HTML::LCParser->new(\$metastring);
  145:         my $token;
  146:         while ($token=$parser->get_token) {
  147:            if ($token->[0] eq 'S') {
  148: 	      my $entry=$token->[1];
  149:               my $unikey=$entry;
  150:               if (defined($token->[2]->{'package'})) { 
  151:                   $unikey.='_package_'.$token->[2]->{'package'};
  152:               } 
  153:               if (defined($token->[2]->{'part'})) { 
  154:                  $unikey.='_'.$token->[2]->{'part'}; 
  155: 	      }
  156:               if (defined($token->[2]->{'id'})) { 
  157:                   $unikey.='_'.$token->[2]->{'id'};
  158:               } 
  159:               if (defined($token->[2]->{'name'})) { 
  160:                  $unikey.='_'.$token->[2]->{'name'}; 
  161: 	      }
  162:               foreach (@{$token->[3]}) {
  163: 		  $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
  164:                   if ($metadatakeys{$unikey}) {
  165: 		      $metadatakeys{$unikey}.=','.$_;
  166:                   } else {
  167:                       $metadatakeys{$unikey}=$_;
  168:                   }
  169:               }
  170:               if ($metadatafields{$unikey}) {
  171: 		  my $newentry=$parser->get_text('/'.$entry);
  172:                   unless (($metadatafields{$unikey}=~/$newentry/) ||
  173:                           ($newentry eq '')) {
  174:                      $metadatafields{$unikey}.=', '.$newentry;
  175: 		  }
  176: 	      } else {
  177:                  $metadatafields{$unikey}=$parser->get_text('/'.$entry);
  178:               }
  179:           }
  180:        }
  181: }
  182: 
  183: #########################################
  184: #########################################
  185: 
  186: =pod
  187: 
  188: =item metaread
  189: 
  190: Read a metadata file
  191: 
  192: =cut
  193: 
  194: #########################################
  195: #########################################
  196: sub metaread {
  197:     my ($logfile,$fn)=@_;
  198:     unless (-e $fn) {
  199: 	print $logfile 'No file '.$fn."\n";
  200:         return '<br><b>No file:</b> <tt>'.$fn.'</tt>';
  201:     }
  202:     print $logfile 'Processing '.$fn."\n";
  203:     my $metastring;
  204:     {
  205:      my $metafh=Apache::File->new($fn);
  206:      $metastring=join('',<$metafh>);
  207:     }
  208:     &metaeval($metastring);
  209:     return '<br><b>Processed file:</b> <tt>'.$fn.'</tt>';
  210: }
  211: 
  212: #########################################
  213: #########################################
  214: 
  215: =pod
  216: 
  217: =item sqltime
  218: 
  219: Convert 'time' format into a datetime sql format
  220: 
  221: =cut
  222: 
  223: #########################################
  224: #########################################
  225: sub sqltime {
  226:     my $timef=shift @_;
  227:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  228: 	localtime($timef);
  229:     $mon++; $year+=1900;
  230:     return "$year-$mon-$mday $hour:$min:$sec";
  231: }
  232: 
  233: 
  234: #########################################
  235: #########################################
  236: 
  237: =pod
  238: 
  239: =item Form field generating functions
  240: 
  241: =over 4
  242: 
  243: =item textfield
  244: 
  245: =item hiddenfield
  246: 
  247: =item selectbox
  248: 
  249: =back
  250: 
  251: =cut
  252: 
  253: #########################################
  254: #########################################
  255: sub textfield {
  256:     my ($title,$name,$value)=@_;
  257:     return "\n<p><b>$title:</b><br>".
  258:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
  259: }
  260: 
  261: sub hiddenfield {
  262:     my ($name,$value)=@_;
  263:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
  264: }
  265: 
  266: sub selectbox {
  267:     my ($title,$name,$value,$functionref,@idlist)=@_;
  268:     my $uctitle=uc($title);
  269:     my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
  270: 	"</b></font><br />".'<select name="'.$name.'">';
  271:     foreach (@idlist) {
  272:         $selout.='<option value=\''.$_.'\'';
  273:         if ($_ eq $value) {
  274: 	    $selout.=' selected>'.&{$functionref}($_).'</option>';
  275: 	}
  276:         else {$selout.='>'.&{$functionref}($_).'</option>';}
  277:     }
  278:     return $selout.'</select>';
  279: }
  280: 
  281: #########################################
  282: #########################################
  283: 
  284: =pod
  285: 
  286: =item urlfixup
  287: 
  288: Fix up a url?  First step of publication
  289: 
  290: =cut
  291: 
  292: #########################################
  293: #########################################
  294: sub urlfixup {
  295:     my ($url,$target)=@_;
  296:     unless ($url) { return ''; }
  297:     #javascript code needs no fixing
  298:     if ($url =~ /^javascript:/i) { return $url; }
  299:     if ($url =~ /^mailto:/i) { return $url; }
  300:     #internal document links need no fixing
  301:     if ($url =~ /^\#/) { return $url; } 
  302:     my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
  303:     foreach (values %Apache::lonnet::hostname) {
  304: 	if ($_ eq $host) {
  305: 	    $url=~s/^http\:\/\///;
  306:             $url=~s/^$host//;
  307:         }
  308:     }
  309:     if ($url=~/^http\:\/\//) { return $url; }
  310:     $url=~s/\~$cuname/res\/$cudom\/$cuname/;
  311:     return $url;
  312: }
  313: 
  314: #########################################
  315: #########################################
  316: 
  317: =pod
  318: 
  319: =item absoluteurl
  320: 
  321: Currently undocumented    
  322: 
  323: =cut
  324: 
  325: #########################################
  326: #########################################
  327: sub absoluteurl {
  328:     my ($url,$target)=@_;
  329:     unless ($url) { return ''; }
  330:     if ($target) {
  331: 	$target=~s/\/[^\/]+$//;
  332:        $url=&Apache::lonnet::hreflocation($target,$url);
  333:     }
  334:     return $url;
  335: }
  336: 
  337: #########################################
  338: #########################################
  339: 
  340: =pod
  341: 
  342: =item set_allow
  343: 
  344: Currently undocumented    
  345: 
  346: =cut
  347: 
  348: #########################################
  349: #########################################
  350: sub set_allow {
  351:     my ($allow,$logfile,$target,$tag,$oldurl)=@_;
  352:     my $newurl=&urlfixup($oldurl,$target);
  353:     my $return_url=$oldurl;
  354:     print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
  355:     if ($newurl ne $oldurl) {
  356: 	$return_url=$newurl;
  357: 	print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
  358:     }
  359:     if (($newurl !~ /^javascript:/i) &&
  360: 	($newurl !~ /^mailto:/i) &&
  361: 	($newurl !~ /^http:/i) &&
  362: 	($newurl !~ /^\#/)) {
  363: 	$$allow{&absoluteurl($newurl,$target)}=1;
  364:     }
  365:     return $return_url
  366: }
  367: 
  368: #########################################
  369: #########################################
  370: 
  371: =pod
  372: 
  373: =item get_subscribed_hosts
  374: 
  375: Currently undocumented    
  376: 
  377: =cut
  378: 
  379: #########################################
  380: #########################################
  381: sub get_subscribed_hosts {
  382:     my ($target)=@_;
  383:     my @subscribed;
  384:     my $filename;
  385:     $target=~/(.*)\/([^\/]+)$/;
  386:     my $srcf=$2;
  387:     opendir(DIR,$1);
  388:     while ($filename=readdir(DIR)) {
  389: 	if ($filename=~/$srcf\.(\w+)$/) {
  390: 	    my $subhost=$1;
  391: 	    if ($subhost ne 'meta' && $subhost ne 'subscription') {
  392: 		push(@subscribed,$subhost);
  393: 	    }
  394: 	}
  395:     }
  396:     closedir(DIR);
  397:     my $sh;
  398:     if ( $sh=Apache::File->new("$target.subscription") ) {
  399: 	&Apache::lonnet::logthis("opened $target.subscription");
  400: 	while (my $subline=<$sh>) {
  401: 	    &Apache::lonnet::logthis("Trying $subline");
  402: 	    if ($subline =~ /(^\w+):/) { push(@subscribed,$1); } else {
  403: 		&Apache::lonnet::logthis("No Match for $subline");
  404: 	    }
  405: 	}
  406:     } else {
  407: 	&Apache::lonnet::logthis("Un able to open $target.subscription");
  408:     }
  409:     &Apache::lonnet::logthis("Got list of ".join(':',@subscribed));
  410:     return @subscribed;
  411: }
  412: 
  413: 
  414: #########################################
  415: #########################################
  416: 
  417: =pod
  418: 
  419: =item get_max_ids_indices
  420: 
  421: Currently undocumented    
  422: 
  423: =cut
  424: 
  425: #########################################
  426: #########################################
  427: sub get_max_ids_indices {
  428:     my ($content)=@_;
  429:     my $maxindex=10;
  430:     my $maxid=10;
  431:     my $needsfixup=0;
  432: 
  433:     my $parser=HTML::LCParser->new($content);
  434:     my $token;
  435:     while ($token=$parser->get_token) {
  436: 	if ($token->[0] eq 'S') {
  437: 	    my $counter;
  438: 	    if ($counter=$addid{$token->[1]}) {
  439: 		if ($counter eq 'id') {
  440: 		    if (defined($token->[2]->{'id'})) {
  441: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
  442: 		    } else {
  443: 			$needsfixup=1;
  444: 		    }
  445: 		} else {
  446: 		    if (defined($token->[2]->{'index'})) {
  447: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
  448: 		    } else {
  449: 			$needsfixup=1;
  450: 		    }
  451: 		}
  452: 	    }
  453: 	}
  454:     }
  455:     return ($needsfixup,$maxid,$maxindex);
  456: }
  457: 
  458: #########################################
  459: #########################################
  460: 
  461: =pod
  462: 
  463: =item get_all_text_unbalanced
  464: 
  465: Currently undocumented    
  466: 
  467: =cut
  468: 
  469: #########################################
  470: #########################################
  471: sub get_all_text_unbalanced {
  472:     #there is a copy of this in lonxml.pm
  473:     my($tag,$pars)= @_;
  474:     my $token;
  475:     my $result='';
  476:     $tag='<'.$tag.'>';
  477:     while ($token = $$pars[-1]->get_token) {
  478: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  479: 	    $result.=$token->[1];
  480: 	} elsif ($token->[0] eq 'PI') {
  481: 	    $result.=$token->[2];
  482: 	} elsif ($token->[0] eq 'S') {
  483: 	    $result.=$token->[4];
  484: 	} elsif ($token->[0] eq 'E')  {
  485: 	    $result.=$token->[2];
  486: 	}
  487: 	if ($result =~ /(.*)$tag(.*)/) {
  488: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
  489: 	    #&Apache::lonnet::logthis('Result is :'.$1);
  490: 	    $result=$1;
  491: 	    my $redo=$tag.$2;
  492: 	    push (@$pars,HTML::LCParser->new(\$redo));
  493: 	    $$pars[-1]->xml_mode('1');
  494: 	    last;
  495: 	}
  496:     }
  497:     return $result
  498: }
  499: 
  500: #########################################
  501: #########################################
  502: 
  503: =pod
  504: 
  505: =item fix_ids_and_indices
  506: 
  507: Currently undocumented    
  508: 
  509: =cut
  510: 
  511: #########################################
  512: #########################################
  513: #Arguably this should all be done as a lonnet::ssi instead
  514: sub fix_ids_and_indices {
  515:     my ($logfile,$source,$target)=@_;
  516: 
  517:     my %allow;
  518:     my $content;
  519:     {
  520: 	my $org=Apache::File->new($source);
  521: 	$content=join('',<$org>);
  522:     }
  523: 
  524:     my ($needsfixup,$maxid,$maxindex)=&get_max_ids_indices(\$content);
  525: 
  526:     if ($needsfixup) {
  527: 	print $logfile "Needs ID and/or index fixup\n".
  528: 	    "Max ID   : $maxid (min 10)\n".
  529:                 "Max Index: $maxindex (min 10)\n";
  530:     }
  531:     my $outstring='';
  532:     my @parser;
  533:     $parser[0]=HTML::LCParser->new(\$content);
  534:     $parser[-1]->xml_mode(1);
  535:     my $token;
  536:     while (@parser) {
  537: 	while ($token=$parser[-1]->get_token) {
  538: 	    if ($token->[0] eq 'S') {
  539: 		my $counter;
  540: 		my $tag=$token->[1];
  541: 		my $lctag=lc($tag);
  542: 		if ($lctag eq 'allow') {
  543: 		    $allow{$token->[2]->{'src'}}=1;
  544: 		    next;
  545: 		}
  546: 		my %parms=%{$token->[2]};
  547: 		$counter=$addid{$tag};
  548: 		if (!$counter) { $counter=$addid{$lctag}; }
  549: 		if ($counter) {
  550: 		    if ($counter eq 'id') {
  551: 			unless (defined($parms{'id'})) {
  552: 			    $maxid++;
  553: 			    $parms{'id'}=$maxid;
  554: 			    print $logfile 'ID: '.$tag.':'.$maxid."\n";
  555: 			}
  556: 		    } elsif ($counter eq 'index') {
  557: 			unless (defined($parms{'index'})) {
  558: 			    $maxindex++;
  559: 			    $parms{'index'}=$maxindex;
  560: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
  561: 			}
  562: 		    }
  563: 		}
  564: 		foreach my $type ('src','href','background','bgimg') {
  565: 		    foreach my $key (keys(%parms)) {
  566: 			if ($key =~ /^$type$/i) {
  567: 			    $parms{$key}=&set_allow(\%allow,$logfile,
  568: 						    $target,$tag,
  569: 						    $parms{$key});
  570: 			}
  571: 		    }
  572: 		}
  573: 		# probably a <randomlabel> image type <label>
  574: 		if ($lctag eq 'label' && defined($parms{'description'})) {
  575: 		    my $next_token=$parser[-1]->get_token();
  576: 		    if ($next_token->[0] eq 'T') {
  577: 			$next_token->[1]=&set_allow(\%allow,$logfile,
  578: 						    $target,$tag,
  579: 						    $next_token->[1]);
  580: 		    }
  581: 		    $parser[-1]->unget_token($next_token);
  582: 		}
  583: 		if ($lctag eq 'applet') {
  584: 		    my $codebase='';
  585: 		    if (defined($parms{'codebase'})) {
  586: 			my $oldcodebase=$parms{'codebase'};
  587: 			unless ($oldcodebase=~/\/$/) {
  588: 			    $oldcodebase.='/';
  589: 			}
  590: 			$codebase=&urlfixup($oldcodebase,$target);
  591: 			$codebase=~s/\/$//;    
  592: 			if ($codebase ne $oldcodebase) {
  593: 			    $parms{'codebase'}=$codebase;
  594: 			    print $logfile 'URL codebase: '.$tag.':'.
  595: 				$oldcodebase.' - '.
  596: 				    $codebase."\n";
  597: 			}
  598: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
  599: 		    } else {
  600: 			foreach ('archive','code','object') {
  601: 			    if (defined($parms{$_})) {
  602: 				my $oldurl=$parms{$_};
  603: 				my $newurl=&urlfixup($oldurl,$target);
  604: 				$newurl=~s/\/[^\/]+$/\/\*/;
  605: 				print $logfile 'Allow: applet '.$_.':'.
  606: 				    $oldurl.' allows '.
  607: 					$newurl."\n";
  608: 				$allow{&absoluteurl($newurl,$target)}=1;
  609: 			    }
  610: 			}
  611: 		    }
  612: 		}
  613: 		my $newparmstring='';
  614: 		my $endtag='';
  615: 		foreach (keys %parms) {
  616: 		    if ($_ eq '/') {
  617: 			$endtag=' /';
  618: 		    } else { 
  619: 			my $quote=($parms{$_}=~/\"/?"'":'"');
  620: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
  621: 		    }
  622: 		}
  623: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  624: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
  625: 		if ($lctag eq 'm') {
  626: 		    $outstring.=&get_all_text_unbalanced('/m',\@parser);
  627: 		}
  628: 	    } elsif ($token->[0] eq 'E') {
  629: 		if ($token->[2]) {
  630: 		    unless ($token->[1] eq 'allow') {
  631: 			$outstring.='</'.$token->[1].'>';
  632: 		    }
  633: 		}
  634: 	    } else {
  635: 		$outstring.=$token->[1];
  636: 	    }
  637: 	}
  638: 	pop(@parser);
  639:     }
  640: 
  641:     if ($needsfixup) {
  642: 	print $logfile "End of ID and/or index fixup\n".
  643: 	    "Max ID   : $maxid (min 10)\n".
  644: 		"Max Index: $maxindex (min 10)\n";
  645:     } else {
  646: 	print $logfile "Does not need ID and/or index fixup\n";
  647:     }
  648: 
  649:     return ($outstring,%allow);
  650: }
  651: 
  652: #########################################
  653: #########################################
  654: 
  655: =pod
  656: 
  657: =item store_metadata
  658: 
  659: Store the metadata in the metadata table in the loncapa database.
  660: Uses lonmysql to access the database.
  661: 
  662: Inputs: \%metadata
  663: 
  664: Returns: (error,status).  error is undef on success, status is undef on error.
  665: 
  666: =cut
  667: 
  668: #########################################
  669: #########################################
  670: sub store_metadata {
  671:     my %metadata = %{shift()};
  672:     my $error;
  673:     # Determine if the table exists
  674:     my $status = &Apache::lonmysql::check_table('metadata');
  675:     if (! defined($status)) {
  676:         $error='<font color="red">WARNING: Cannot connect to '.
  677:             'database!</font>';
  678:         &Apache::lonnet::logthis($error);
  679:         return ($error,undef);
  680:     }
  681:     if ($status == 0) {
  682:         # It would be nice to actually create the table....
  683:         $error ='<font color="red">WARNING: The metadata table does not '.
  684:             'exist in the LON-CAPA database.</font>';
  685:         &Apache::lonnet::logthis($error);
  686:         return ($error,undef);
  687:     }
  688:     # Remove old value from table
  689:     $status = &Apache::lonmysql::remove_from_table
  690:         ('metadata','url',$metadata{'url'});
  691:     if (! defined($status)) {
  692:         $error = '<font color="red">Error when removing old values from '.
  693:             'metadata table in LON-CAPA database.</font>';
  694:         &Apache::lonnet::logthis($error);
  695:         return ($error,undef);
  696:     }
  697:     # Store data in table.
  698:     $status = &Apache::lonmysql::store_row('metadata',\%metadata);
  699:     if (! defined($status)) {
  700:         $error='<font color="red">Error occured storing new values in '.
  701:             'metadata table in LON-CAPA database</font>';
  702:         &Apache::lonnet::logthis($error);
  703:         return ($error,undef);
  704:     }
  705:     return (undef,$status);
  706: }
  707: 
  708: #########################################
  709: #########################################
  710: 
  711: =pod
  712: 
  713: =item publish
  714: 
  715: Currently undocumented.  This is the workhorse function of this module.
  716: 
  717: =cut
  718: 
  719: #########################################
  720: #########################################
  721: sub publish {
  722: 
  723:     my ($source,$target,$style)=@_;
  724:     my $logfile;
  725:     my $scrout='';
  726:     my $allmeta='';
  727:     my $content='';
  728:     my %allow=();
  729: 
  730:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  731: 	return 
  732:          '<font color=red>No write permission to user directory, FAIL</font>';
  733:     }
  734:     print $logfile 
  735: "\n\n================= Publish ".localtime()." Phase One  ================\n";
  736: 
  737:     if (($style eq 'ssi') || ($style eq 'rat')) {
  738: # ------------------------------------------------------- This needs processing
  739: 
  740: # ----------------------------------------------------------------- Backup Copy
  741: 	my $copyfile=$source.'.save';
  742:         if (copy($source,$copyfile)) {
  743: 	    print $logfile "Copied original file to ".$copyfile."\n";
  744:         } else {
  745: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
  746:           return "<font color=red>Failed to write backup copy, $!,FAIL</font>";
  747:         }
  748: # ------------------------------------------------------------- IDs and indices
  749: 	
  750: 	my $outstring;
  751: 	($outstring,%allow)=&fix_ids_and_indices($logfile,$source,$target);
  752: # ------------------------------------------------------------ Construct Allows
  753:     
  754: 	$scrout.='<h3>Dependencies</h3>';
  755:         my $allowstr='';
  756:         foreach (sort(keys(%allow))) {
  757: 	   my $thisdep=$_;
  758: 	   if ($thisdep !~ /[^\s]/) { next; }
  759:            unless ($style eq 'rat') { 
  760:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
  761: 	   }
  762:            $scrout.='<br>';
  763:            unless ($thisdep=~/\*/) {
  764: 	       $scrout.='<a href="'.$thisdep.'">';
  765:            }
  766:            $scrout.='<tt>'.$thisdep.'</tt>';
  767:            unless ($thisdep=~/\*/) {
  768: 	       $scrout.='</a>';
  769:                if (
  770:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
  771:                                             $thisdep.'.meta') eq '-1') {
  772: 		   $scrout.=
  773:                            ' - <font color=red>Currently not available</font>';
  774:                } else {
  775:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
  776:                              &Apache::lonnet::declutter($thisdep).'___usage'
  777:                                  => time);
  778:                    $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
  779:                    if ((defined($1)) && (defined($2))) {
  780:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
  781: 					   $1,$2);
  782: 		   }
  783: 	       }
  784:            }
  785:         }
  786:         $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
  787: 
  788: 	#Encode any High ASCII characters
  789: 	$outstring=&HTML::Entities::encode($outstring,"\200-\377");
  790: # ------------------------------------------------------------- Write modified
  791: 
  792:         {
  793:           my $org;
  794:           unless ($org=Apache::File->new('>'.$source)) {
  795:              print $logfile "No write permit to $source\n";
  796:              return 
  797:               "<font color=red>No write permission to $source, FAIL</font>";
  798: 	  }
  799:           print $org $outstring;
  800:         }
  801: 	  $content=$outstring;
  802: 
  803:     }
  804: # --------------------------------------------- Initial step done, now metadata
  805: 
  806: # ---------------------------------------- Storage for metadata keys and fields
  807: 
  808:      %metadatafields=();
  809:      %metadatakeys=();
  810:      
  811:      my %oldparmstores=();
  812:      
  813:      
  814:      $scrout.='<h3>Metadata Information ' .
  815:        Apache::loncommon::help_open_topic("Metadata_Description")
  816:        . '</h3>';
  817: 
  818: # ------------------------------------------------ First, check out environment
  819:      unless (-e $source.'.meta') {
  820:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
  821: 	                          $ENV{'environment.middlename'}.' '.
  822: 		                  $ENV{'environment.lastname'}.' '.
  823: 		                  $ENV{'environment.generation'};
  824:         $metadatafields{'author'}=~s/\s+/ /g;
  825:         $metadatafields{'author'}=~s/\s+$//;
  826:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
  827: 
  828: # ------------------------------------------------ Check out directory hierachy
  829: 
  830:         my $thisdisfn=$source;
  831:         $thisdisfn=~s/^\/home\/$cuname\///;
  832: 
  833:         my @urlparts=split(/\//,$thisdisfn);
  834:         $#urlparts--;
  835: 
  836:         my $currentpath='/home/'.$cuname.'/';
  837: 
  838:         foreach (@urlparts) {
  839: 	    $currentpath.=$_.'/';
  840:             $scrout.=&metaread($logfile,$currentpath.'default.meta');
  841:         }
  842: 
  843: # ------------------- Clear out parameters and stores (there should not be any)
  844: 
  845:         foreach (keys %metadatafields) {
  846: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  847: 		delete $metadatafields{$_};
  848:             }
  849:         }
  850: 
  851:     } else {
  852: # ---------------------- Read previous metafile, remember parameters and stores
  853: 
  854:         $scrout.=&metaread($logfile,$source.'.meta');
  855: 
  856:         foreach (keys %metadatafields) {
  857: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  858:                 $oldparmstores{$_}=1;
  859: 		delete $metadatafields{$_};
  860:             }
  861:         }
  862:         
  863:     }
  864: 
  865: # -------------------------------------------------- Parse content for metadata
  866:     if ($style eq 'ssi') {
  867:         my $oldenv=$ENV{'request.uri'};
  868: 
  869:         $ENV{'request.uri'}=$target;
  870:         $allmeta=Apache::lonxml::xmlparse(undef,'meta',$content);
  871:         $ENV{'request.uri'}=$oldenv;
  872: 
  873:         &metaeval($allmeta);
  874:     }
  875: # ---------------- Find and document discrepancies in the parameters and stores
  876: 
  877:         my $chparms='';
  878:         foreach (sort keys %metadatafields) {
  879: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  880:                 unless ($_=~/\.\w+$/) { 
  881:                    unless ($oldparmstores{$_}) {
  882: 		      print $logfile 'New: '.$_."\n";
  883:                       $chparms.=$_.' ';
  884:                    }
  885: 	        }
  886:             }
  887:         }
  888:         if ($chparms) {
  889: 	    $scrout.='<p><b>New parameters or stored values:</b> '.
  890:                      $chparms;
  891:         }
  892: 
  893:         $chparms='';
  894:         foreach (sort keys %oldparmstores) {
  895: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  896:                 unless (($metadatafields{$_.'.name'}) ||
  897:                         ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
  898: 		    print $logfile 'Obsolete: '.$_."\n";
  899:                     $chparms.=$_.' ';
  900:                 }
  901:             }
  902:         }
  903:         if ($chparms) {
  904: 	    $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
  905:                      $chparms;
  906:         }
  907: 
  908: # ------------------------------------------------------- Now have all metadata
  909: 
  910:         $scrout.=
  911:      '<form name="pubform" action="/adm/publish" method="post">'.
  912:        '<p><input type="submit" value="Finalize Publication" /></p>'.
  913:           &hiddenfield('phase','two').
  914:           &hiddenfield('filename',$ENV{'form.filename'}).
  915: 	  &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
  916:           &hiddenfield('dependencies',join(',',keys %allow)).
  917:           &textfield('Title','title',$metadatafields{'title'}).
  918:           &textfield('Author(s)','author',$metadatafields{'author'}).
  919: 	  &textfield('Subject','subject',$metadatafields{'subject'});
  920: 
  921: # --------------------------------------------------- Scan content for keywords
  922: 
  923:         my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
  924: 	my $keywordout=<<"END";
  925: <script>
  926: function checkAll(field)
  927: {
  928:     for (i = 0; i < field.length; i++)
  929:         field[i].checked = true ;
  930: }
  931: 
  932: function uncheckAll(field)
  933: {
  934:     for (i = 0; i < field.length; i++)
  935:         field[i].checked = false ;
  936: }
  937: </script>
  938: <p><b>Keywords: $keywords_help</b> 
  939: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)"> 
  940: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)"> 
  941: <br />
  942: END
  943:         $keywordout.='<table border=2><tr>';
  944:         my $colcount=0;
  945:         my %keywords=();
  946:         
  947: 	if (length($content)<500000) {
  948: 	    my $textonly=$content;
  949:             $textonly=~s/\<script[^\<]+\<\/script\>//g;
  950:             $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
  951:             $textonly=~s/\<[^\>]*\>//g;
  952:             $textonly=~tr/A-Z/a-z/;
  953:             $textonly=~s/[\$\&][a-z]\w*//g;
  954:             $textonly=~s/[^a-z\s]//g;
  955: 
  956:             foreach ($textonly=~m/(\w+)/g) {
  957: 		unless ($nokey{$_}) {
  958:                    $keywords{$_}=1;
  959:                 } 
  960:             }
  961:         }
  962: 
  963:             
  964:             foreach (split(/\W+/,$metadatafields{'keywords'})) {
  965: 		$keywords{$_}=1;
  966:             }
  967: 
  968:             foreach (sort keys %keywords) {
  969:                 $keywordout.='<td><input type=checkbox name="keywords" value="'.$_.'"';
  970:                 if ($metadatafields{'keywords'}) {
  971:                    if ($metadatafields{'keywords'}=~/$_/) { 
  972:                       $keywordout.=' checked'; 
  973:                    }
  974: 	        } elsif (&Apache::loncommon::keyword($_)) {
  975: 	            $keywordout.=' checked';
  976:                 } 
  977:                 $keywordout.='>'.$_.'</td>';
  978:                 if ($colcount>10) {
  979: 		    $keywordout.="</tr><tr>\n";
  980:                     $colcount=0;
  981:                 }
  982:                 $colcount++;
  983:             }
  984:         
  985: 	$keywordout.='</tr></table>';
  986: 
  987:         $scrout.=$keywordout;
  988: 
  989:         $scrout.=&textfield('Additional Keywords','addkey','');
  990: 
  991:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
  992: 
  993:         $scrout.=
  994:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
  995:               $metadatafields{'abstract'}.'</textarea>';
  996: 
  997: 	$source=~/\.(\w+)$/;
  998: 
  999: 	$scrout.=&hiddenfield('mime',$1);
 1000: 
 1001:         $scrout.=&selectbox('Language','language',
 1002:                             $metadatafields{'language'},
 1003: 			    \&Apache::loncommon::languagedescription,
 1004: 			    (&Apache::loncommon::languageids),
 1005: 			     );
 1006: 
 1007:         unless ($metadatafields{'creationdate'}) {
 1008: 	    $metadatafields{'creationdate'}=time;
 1009:         }
 1010:         $scrout.=&hiddenfield('creationdate',$metadatafields{'creationdate'});
 1011: 
 1012:         $scrout.=&hiddenfield('lastrevisiondate',time);
 1013: 
 1014: 			   
 1015: 	$scrout.=&textfield('Publisher/Owner','owner',
 1016:                             $metadatafields{'owner'});
 1017: # --------------------------------------------------- Correct copyright for rat        
 1018: 
 1019:     if ($style eq 'rat') {
 1020: 	if ($metadatafields{'copyright'} eq 'public') { 
 1021: 	    delete $metadatafields{'copyright'};
 1022: 	}
 1023:         $scrout.=&selectbox('Copyright/Distribution','copyright',
 1024:                             $metadatafields{'copyright'},
 1025: 			    \&Apache::loncommon::copyrightdescription,
 1026: 		     (grep !/^public$/,(&Apache::loncommon::copyrightids)));
 1027:     }
 1028:     else {
 1029:         $scrout.=&selectbox('Copyright/Distribution','copyright',
 1030:                             $metadatafields{'copyright'},
 1031: 			    \&Apache::loncommon::copyrightdescription,
 1032: 			     (&Apache::loncommon::copyrightids));
 1033:     }
 1034: 
 1035:     my $copyright_help = Apache::loncommon::help_open_topic("Publishing_Copyright");
 1036:     $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
 1037:     return $scrout.
 1038:       '<p><input type="submit" value="Finalize Publication" /></p></form>';
 1039: }
 1040: 
 1041: #########################################
 1042: #########################################
 1043: 
 1044: =pod 
 1045: 
 1046: =item phasetwo
 1047: 
 1048: Render second interface showing status of publication steps.
 1049: This is publication step two.
 1050: 
 1051: =cut
 1052: 
 1053: #########################################
 1054: #########################################
 1055: sub phasetwo {
 1056: 
 1057:     my ($source,$target,$style,$distarget)=@_;
 1058:     my $logfile;
 1059:     my $scrout='';
 1060:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
 1061: 	return 
 1062:          '<font color=red>No write permission to user directory, FAIL</font>';
 1063:     }
 1064:     print $logfile 
 1065: "\n================= Publish ".localtime()." Phase Two  ================\n";
 1066: 
 1067:      %metadatafields=();
 1068:      %metadatakeys=();
 1069: 
 1070:      &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
 1071: 
 1072:      $metadatafields{'title'}=$ENV{'form.title'};
 1073:      $metadatafields{'author'}=$ENV{'form.author'};
 1074:      $metadatafields{'subject'}=$ENV{'form.subject'};
 1075:      $metadatafields{'notes'}=$ENV{'form.notes'};
 1076:      $metadatafields{'abstract'}=$ENV{'form.abstract'};
 1077:      $metadatafields{'mime'}=$ENV{'form.mime'};
 1078:      $metadatafields{'language'}=$ENV{'form.language'};
 1079:      $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
 1080:      $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
 1081:      $metadatafields{'owner'}=$ENV{'form.owner'};
 1082:      $metadatafields{'copyright'}=$ENV{'form.copyright'};
 1083:      $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
 1084: 
 1085:      my $allkeywords=$ENV{'form.addkey'};
 1086:      if (exists($ENV{'form.keywords'}) && (ref($ENV{'form.keywords'}))) {
 1087:          my @Keywords = @{$ENV{'form.keywords'}};
 1088:          foreach (@Keywords) {
 1089:              $allkeywords.=','.$_;
 1090:          }
 1091:      }
 1092:      $allkeywords=~s/\W+/\,/;
 1093:      $allkeywords=~s/^\,//;
 1094:      $metadatafields{'keywords'}=$allkeywords;
 1095:  
 1096:      {
 1097:        print $logfile "\nWrite metadata file for ".$source;
 1098:        my $mfh;
 1099:        unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
 1100: 	return 
 1101:          '<font color=red>Could not write metadata, FAIL</font>';
 1102:        }
 1103:        foreach (sort keys %metadatafields) {
 1104: 	 unless ($_=~/\./) {
 1105:            my $unikey=$_;
 1106:            $unikey=~/^([A-Za-z]+)/;
 1107:            my $tag=$1;
 1108:            $tag=~tr/A-Z/a-z/;
 1109:            print $mfh "\n\<$tag";
 1110:            foreach (split(/\,/,$metadatakeys{$unikey})) {
 1111:                my $value=$metadatafields{$unikey.'.'.$_};
 1112:                $value=~s/\"/\'\'/g;
 1113:                print $mfh ' '.$_.'="'.$value.'"';
 1114:            }
 1115: 	   print $mfh '>'.
 1116: 	     &HTML::Entities::encode($metadatafields{$unikey})
 1117: 	       .'</'.$tag.'>';
 1118:          }
 1119:        }
 1120:        $scrout.='<p>Wrote Metadata';
 1121:        print $logfile "\nWrote metadata";
 1122:      }
 1123: 
 1124: # -------------------------------- Synchronize entry with SQL metadata database
 1125:     my $warning;
 1126:     $metadatafields{'url'} = $distarget;
 1127:     $metadatafields{'version'} = 'current';
 1128:     unless ($metadatafields{'copyright'} eq 'priv') {
 1129:         my ($error,$success) = &store_metadata(\%metadatafields);
 1130:         if ($success) {
 1131:             $scrout.='<p>Synchronized SQL metadata database';
 1132:             print $logfile "\nSynchronized SQL metadata database";
 1133:         } else {
 1134:             $warning.=$error;
 1135:             print $logfile "\n".$error;
 1136:         }
 1137:     } else {
 1138:         $scrout.='<p>Private Publication - did not synchronize database';
 1139:         print $logfile "\nPrivate: Did not synchronize data into ".
 1140:             "SQL metadata database";
 1141:     }
 1142: # ----------------------------------------------------------- Copy old versions
 1143:    
 1144: if (-e $target) {
 1145:     my $filename;
 1146:     my $maxversion=0;
 1147:     $target=~/(.*)\/([^\/]+)\.(\w+)$/;
 1148:     my $srcf=$2;
 1149:     my $srct=$3;
 1150:     my $srcd=$1;
 1151:     unless ($srcd=~/^\/home\/httpd\/html\/res/) {
 1152: 	print $logfile "\nPANIC: Target dir is ".$srcd;
 1153:         return "<font color=red>Invalid target directory, FAIL</font>";
 1154:     }
 1155:     opendir(DIR,$srcd);
 1156:     while ($filename=readdir(DIR)) {
 1157:        if ($filename=~/$srcf\.(\d+)\.$srct$/) {
 1158: 	   $maxversion=($1>$maxversion)?$1:$maxversion;
 1159:        }
 1160:     }
 1161:     closedir(DIR);
 1162:     $maxversion++;
 1163:     $scrout.='<p>Creating old version '.$maxversion;
 1164:     print $logfile "\nCreating old version ".$maxversion;
 1165: 
 1166:     my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
 1167: 
 1168:         if (copy($target,$copyfile)) {
 1169: 	    print $logfile "Copied old target to ".$copyfile."\n";
 1170:             $scrout.='<p>Copied old target file';
 1171:         } else {
 1172: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 1173:            return "<font color=red>Failed to copy old target, $!, FAIL</font>";
 1174:         }
 1175: 
 1176: # --------------------------------------------------------------- Copy Metadata
 1177: 
 1178: 	$copyfile=$copyfile.'.meta';
 1179: 
 1180:         if (copy($target.'.meta',$copyfile)) {
 1181: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
 1182:             $scrout.='<p>Copied old metadata';
 1183:         } else {
 1184: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 1185:             if (-e $target.'.meta') {
 1186:                return 
 1187:        "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
 1188: 	    }
 1189:         }
 1190: 
 1191: 
 1192: } else {
 1193:     $scrout.='<p>Initial version';
 1194:     print $logfile "\nInitial version";
 1195: }
 1196: 
 1197: # ---------------------------------------------------------------- Write Source
 1198: 	my $copyfile=$target;
 1199: 
 1200:            my @parts=split(/\//,$copyfile);
 1201:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1202: 
 1203:            my $count;
 1204:            for ($count=5;$count<$#parts;$count++) {
 1205:                $path.="/$parts[$count]";
 1206:                if ((-e $path)!=1) {
 1207:                    print $logfile "\nCreating directory ".$path;
 1208:                    $scrout.='<p>Created directory '.$parts[$count];
 1209: 		   mkdir($path,0777);
 1210:                }
 1211:            }
 1212: 
 1213:         if (copy($source,$copyfile)) {
 1214: 	    print $logfile "Copied original source to ".$copyfile."\n";
 1215:             $scrout.='<p>Copied source file';
 1216:         } else {
 1217: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 1218:             return "<font color=red>Failed to copy source, $!, FAIL</font>";
 1219:         }
 1220: 
 1221: # --------------------------------------------------------------- Copy Metadata
 1222: 
 1223:         $copyfile=$copyfile.'.meta';
 1224: 
 1225:         if (copy($source.'.meta',$copyfile)) {
 1226: 	    print $logfile "Copied original metadata to ".$copyfile."\n";
 1227:             $scrout.='<p>Copied metadata';
 1228:         } else {
 1229: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 1230:             return 
 1231:           "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
 1232:         }
 1233: 
 1234: # --------------------------------------------------- Send update notifications
 1235: 
 1236:     my @subscribed=&get_subscribed_hosts($target);
 1237:     foreach my $subhost (@subscribed) {
 1238: 	$scrout.='<p>Notifying host '.$subhost.':';
 1239: 	print $logfile "\nNotifying host ".$subhost.':';
 1240: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 1241: 	$scrout.=$reply;
 1242: 	print $logfile $reply;
 1243:     }
 1244: 
 1245: # ---------------------------------------- Send update notifications, meta only
 1246: 
 1247:     my @subscribedmeta=&get_subscribed_hosts("$target.meta");
 1248:     foreach my $subhost (@subscribedmeta) {
 1249: 	$scrout.='<p>Notifying host for metadata only '.$subhost.':';
 1250: 	print $logfile "\nNotifying host for metadata only ".$subhost.':';
 1251: 	my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 1252: 					    $subhost);
 1253: 	$scrout.=$reply;
 1254: 	print $logfile $reply;
 1255:     }
 1256: 
 1257: # ------------------------------------------------ Provide link to new resource
 1258: 
 1259:     my $thisdistarget=$target;
 1260:     $thisdistarget=~s/^$docroot//;
 1261: 
 1262:     my $thissrc=$source;
 1263:     $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
 1264: 
 1265:     my $thissrcdir=$thissrc;
 1266:     $thissrcdir=~s/\/[^\/]+$/\//;
 1267: 
 1268: 
 1269:     return $warning.$scrout.
 1270:       '<hr><a href="'.$thisdistarget.'"><font size=+2>View Published Version</font></a>'.
 1271:       '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
 1272:       '<p><a href="'.$thissrcdir.
 1273:       '"><font size=+2>Back to Source Directory</font></a>';
 1274: 
 1275: }
 1276: 
 1277: 
 1278: #########################################
 1279: #########################################
 1280: 
 1281: =pod
 1282: 
 1283: =item handler
 1284: 
 1285: A basic outline of the handler subroutine follows.
 1286: 
 1287: =over 4
 1288: 
 1289: =item Get query string for limited number of parameters
 1290: 
 1291: =item Check filename
 1292: 
 1293: =item File is there and owned, init lookup tables
 1294: 
 1295: =item Start page output
 1296: 
 1297: =item Individual file
 1298: 
 1299: =item publish from $thisfn to $thistarget with $thisembstyle
 1300: 
 1301: =back
 1302: 
 1303: =cut
 1304: 
 1305: #########################################
 1306: #########################################
 1307: sub handler {
 1308:   my $r=shift;
 1309: 
 1310:   if ($r->header_only) {
 1311:      $r->content_type('text/html');
 1312:      $r->send_http_header;
 1313:      return OK;
 1314:   }
 1315: 
 1316: # Get query string for limited number of parameters
 1317: 
 1318:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1319:                                             ['filename']);
 1320: 
 1321: # -------------------------------------------------------------- Check filename
 1322: 
 1323:   my $fn=$ENV{'form.filename'};
 1324: 
 1325:   
 1326:   unless ($fn) { 
 1327:      $r->log_reason($cuname.' at '.$cudom.
 1328:          ' trying to publish empty filename', $r->filename); 
 1329:      return HTTP_NOT_FOUND;
 1330:   } 
 1331: 
 1332:   ($cuname,$cudom)=
 1333:     &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
 1334:   unless (($cuname) && ($cudom)) {
 1335:      $r->log_reason($cuname.' at '.$cudom.
 1336:          ' trying to publish file '.$ENV{'form.filename'}.
 1337:          ' ('.$fn.') - not authorized', 
 1338:          $r->filename); 
 1339:      return HTTP_NOT_ACCEPTABLE;
 1340:   }
 1341: 
 1342:   unless (&Apache::lonnet::homeserver($cuname,$cudom) 
 1343:           eq $r->dir_config('lonHostID')) {
 1344:      $r->log_reason($cuname.' at '.$cudom.
 1345:          ' trying to publish file '.$ENV{'form.filename'}.
 1346:          ' ('.$fn.') - not homeserver ('.
 1347:          &Apache::lonnet::homeserver($cuname,$cudom).')', 
 1348:          $r->filename); 
 1349:      return HTTP_NOT_ACCEPTABLE;
 1350:   }
 1351: 
 1352:   $fn=~s/^http\:\/\/[^\/]+//;
 1353:   $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
 1354: 
 1355:   my $targetdir='';
 1356:   $docroot=$r->dir_config('lonDocRoot'); 
 1357:   if ($1 ne $cuname) {
 1358:      $r->log_reason($cuname.' at '.$cudom.
 1359:          ' trying to publish unowned file '.$ENV{'form.filename'}.
 1360:          ' ('.$fn.')', 
 1361:          $r->filename); 
 1362:      return HTTP_NOT_ACCEPTABLE;
 1363:   } else {
 1364:       $targetdir=$docroot.'/res/'.$cudom;
 1365:   }
 1366:                                  
 1367:   
 1368:   unless (-e $fn) { 
 1369:      $r->log_reason($cuname.' at '.$cudom.
 1370:          ' trying to publish non-existing file '.$ENV{'form.filename'}.
 1371:          ' ('.$fn.')', 
 1372:          $r->filename); 
 1373:      return HTTP_NOT_FOUND;
 1374:   } 
 1375: 
 1376: unless ($ENV{'form.phase'} eq 'two') {
 1377: 
 1378: # --------------------------------- File is there and owned, init lookup tables
 1379: 
 1380:   %addid=();
 1381: 
 1382:   {
 1383:       my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
 1384:       while (<$fh>=~/(\w+)\s+(\w+)/) {
 1385:           $addid{$1}=$2;
 1386:       }
 1387:   }
 1388: 
 1389:   %nokey=();
 1390: 
 1391:   {
 1392:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
 1393:       while (<$fh>) {
 1394:           my $word=$_;
 1395:           chomp($word);
 1396:           $nokey{$word}=1;
 1397:       }
 1398:   }
 1399: 
 1400: }
 1401: 
 1402: # ----------------------------------------------------------- Start page output
 1403: 
 1404:   $r->content_type('text/html');
 1405:   $r->send_http_header;
 1406: 
 1407:   $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
 1408:   $r->print(
 1409:    '<body bgcolor="#FFFFFF"><img align=right src=/adm/lonIcons/lonlogos.gif>');
 1410:   my $thisfn=$fn;
 1411:    
 1412: # ------------------------------------------------------------- Individual file
 1413:   {
 1414:       $thisfn=~/\.(\w+)$/;
 1415:       my $thistype=$1;
 1416:       my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 1417: 
 1418:       my $thistarget=$thisfn;
 1419:       
 1420:       $thistarget=~s/^\/home/$targetdir/;
 1421:       $thistarget=~s/\/public\_html//;
 1422: 
 1423:       my $thisdistarget=$thistarget;
 1424:       $thisdistarget=~s/^$docroot//;
 1425: 
 1426:       my $thisdisfn=$thisfn;
 1427:       $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
 1428: 
 1429:       $r->print('<h2>Publishing '.
 1430:         &Apache::loncommon::filedescription($thistype).' <tt>'.
 1431:         $thisdisfn.'</tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
 1432:    
 1433:        if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
 1434:           $r->print('<h3><font color=red>Co-Author: '.$cuname.' at '.$cudom.
 1435:                '</font></h3>');
 1436:       }
 1437: 
 1438:       if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
 1439:           $r->print('<br><a href="/adm/diff?filename=/~'.$cuname.'/'.
 1440:                     $thisdisfn.
 1441:   	  '&versionone=priv" target=cat>Diffs with Current Version</a><p>');
 1442:       }
 1443:   
 1444: # ------------ We are publishing from $thisfn to $thistarget with $thisembstyle
 1445: 
 1446:        unless ($ENV{'form.phase'} eq 'two') {
 1447:          $r->print(
 1448:           '<hr>'.&publish($thisfn,$thistarget,$thisembstyle));
 1449:        } else {
 1450:          $r->print(
 1451:           '<hr>'.&phasetwo($thisfn,$thistarget,$thisembstyle,$thisdistarget)); 
 1452:        }  
 1453: 
 1454:   }
 1455:   $r->print('</body></html>');
 1456: 
 1457:   return OK;
 1458: }
 1459: 
 1460: 1;
 1461: __END__
 1462: 
 1463: =pod
 1464: 
 1465: =back
 1466: 
 1467: =cut
 1468: 

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