File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.215: download - view: text, annotated - select for diffs
Wed Dec 6 22:22:39 2006 UTC (17 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_2_3_0, version_2_2_99_1, version_2_2_99_0, HEAD
- more re fix ups

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

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