File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.158: download - view: text, annotated - select for diffs
Mon Dec 29 21:17:00 2003 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Small bugfixes, standards and gradelevel info on directory level

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

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