File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.211: download - view: text, annotated - select for diffs
Fri Aug 4 22:16:42 2006 UTC (17 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_2_2_X, version_2_2_1, version_2_2_0, version_2_1_99_3, HEAD
- some @ -> : conversion

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

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