File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.132: download - view: text, annotated - select for diffs
Tue Sep 16 21:30:28 2003 UTC (20 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Fixes BUG#2196, batch publication was bleeding values between publications, (If you didn't set a title everything after the first one to have a title got the same title)

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

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