File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.134: download - view: text, annotated - select for diffs
Mon Sep 22 00:48:32 2003 UTC (20 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Internationalization, German Localization

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

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