File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.221: download - view: text, annotated - select for diffs
Fri Mar 2 23:18:19 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- starting work on moving to distributed DNS, eliminate usage of the lonnet hostanme global

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.221 2007/03/02 23:18:19 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: 	    next if ($entry =~ m/^(?:parameter|stores)_/);
  187: 	    if (defined($token->[2]->{'package'})) { 
  188: 		$unikey.="\0package\0".$token->[2]->{'package'};
  189: 	    } 
  190: 	    if (defined($token->[2]->{'part'})) { 
  191: 		$unikey.="\0".$token->[2]->{'part'}; 
  192: 	    }
  193: 	    if (defined($token->[2]->{'id'})) { 
  194: 		$unikey.="\0".$token->[2]->{'id'};
  195: 	    } 
  196: 	    if (defined($token->[2]->{'name'})) { 
  197: 		$unikey.="\0".$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=~ m{^($match_domain)/($match_username)/});
  285:     my $regexp=quotemeta($url);
  286:     $regexp='___'.$regexp.'___course';
  287:     my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
  288: 				       $aauthor,$regexp);
  289:     my %courses=();
  290:     foreach (keys %evaldata) {
  291: 	if ($_=~/^([a-zA-Z0-9]+_[a-zA-Z0-9]+)___.+___course$/) {
  292: 	    $courses{$1}=1;
  293:         }
  294:     }
  295:     return %courses;
  296: }
  297: #########################################
  298: #########################################
  299: 
  300: 
  301: =pod
  302: 
  303: =item Form-field-generating subroutines.
  304: 
  305: For input parameters, these subroutines take in values
  306: such as I<$name>, I<$value> and other form field metadata.
  307: The output (scalar string that is returned) is an XHTML
  308: string which presents the form field (foreseeably inside
  309: <form></form> tags).
  310: 
  311: =over 4
  312: 
  313: =item B<textfield>
  314: 
  315: =item B<hiddenfield>
  316: 
  317: =item B<selectbox>
  318: 
  319: =back
  320: 
  321: =cut
  322: 
  323: #########################################
  324: #########################################
  325: sub textfield {
  326:     my ($title,$name,$value)=@_;
  327:     $value=~s/^\s+//gs;
  328:     $value=~s/\s+$//gs;
  329:     $value=~s/\s+/ /gs;
  330:     $title=&mt($title);
  331:     $env{'form.'.$name}=$value;
  332:     return "\n<p><font color=\"#800000\" face=\"helvetica\"><b>$title:".
  333:            "</b></font></p><br />".
  334:            '<input type="text" name="'.$name.'" size=80 value="'.$value.'" />';
  335: }
  336: 
  337: sub text_with_browse_field {
  338:     my ($title,$name,$value,$restriction)=@_;
  339:     $value=~s/^\s+//gs;
  340:     $value=~s/\s+$//gs;
  341:     $value=~s/\s+/ /gs;
  342:     $title=&mt($title);
  343:     $env{'form.'.$name}=$value;
  344:     return "\n<p><font color=\"#800000\" face=\"helvetica\"><b>$title:".
  345:            "</b></font></p><br />".
  346:            '<input type="text" name="'.$name.'" size=80 value="'.$value.'" />'.
  347: 	   '<a href="javascript:openbrowser(\'pubform\',\''.$name.'\',\''.$restriction.'\');">Select</a>&nbsp;'.
  348: 	   '<a href="javascript:opensearcher(\'pubform\',\''.$name.'\');">Search</a>';
  349: 	   
  350: }
  351: 
  352: sub hiddenfield {
  353:     my ($name,$value)=@_;
  354:     $env{'form.'.$name}=$value;
  355:     return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
  356: }
  357: 
  358: sub checkbox {
  359:     my ($name,$text)=@_;
  360:     return "\n<br /><label><input type='checkbox' name='$name' /> ".
  361: 	&mt($text)."</label>";
  362: }
  363: 
  364: sub selectbox {
  365:     my ($title,$name,$value,$functionref,@idlist)=@_;
  366:     $title=&mt($title);
  367:     $value=(split(/\s*,\s*/,$value))[-1];
  368:     if (defined($value)) {
  369: 	$env{'form.'.$name}=$value;
  370:     } else {
  371: 	$env{'form.'.$name}=$idlist[0];
  372:     }
  373:     my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$title:".
  374: 	'</b></font></p><br /><select name="'.$name.'">';
  375:     foreach (@idlist) {
  376:         $selout.='<option value=\''.$_.'\'';
  377:         if ($_ eq $value) {
  378: 	    $selout.=' selected>'.&{$functionref}($_).'</option>';
  379: 	}
  380:         else {$selout.='>'.&{$functionref}($_).'</option>';}
  381:     }
  382:     return $selout.'</select>';
  383: }
  384: 
  385: sub select_level_form {
  386:     my ($value,$name)=@_;
  387:     $env{'form.'.$name}=$value;
  388:     if (!defined($value)) { $env{'form.'.$name}=0; }
  389:     return  &Apache::loncommon::select_level_form($value,$name);
  390: }
  391: #########################################
  392: #########################################
  393: 
  394: =pod
  395: 
  396: =item B<urlfixup>
  397: 
  398: Fix up a url?  First step of publication
  399: 
  400: =cut
  401: 
  402: #########################################
  403: #########################################
  404: sub urlfixup {
  405:     my ($url,$target)=@_;
  406:     unless ($url) { return ''; }
  407:     #javascript code needs no fixing
  408:     if ($url =~ /^javascript:/i) { return $url; }
  409:     if ($url =~ /^mailto:/i) { return $url; }
  410:     #internal document links need no fixing
  411:     if ($url =~ /^\#/) { return $url; } 
  412:     my ($host)=($url=~/(?:(?:http|https|ftp)\:\/\/)*([^\/]+)/);
  413:     my %all_hostnames = &Apache::lonnet::all_hostnames();
  414:     foreach my $hostname (values(%all_hostnames)) {
  415: 	if ($hostname eq $host) {
  416: 	    $url=~s/^(?:http|https|ftp)\:\/\///;
  417:             $url=~s/^\Q$host\E//;
  418:         }
  419:     }
  420:     if ($url=~/^(?:http|https|ftp)\:\/\//) { 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|https|ftp):/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\.($match_lonid)$/) {
  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: 	while (my $subline=<$sh>) {
  513: 	    if ($subline =~ /^($match_lonid):/) { 
  514:                 if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) { 
  515:                    push(@subscribed,$1);
  516: 	        }
  517: 	    }
  518: 	}
  519:     }
  520:     return @subscribed;
  521: }
  522: 
  523: 
  524: #########################################
  525: #########################################
  526: 
  527: =pod
  528: 
  529: =item B<get_max_ids_indices>
  530: 
  531: Currently undocumented    
  532: 
  533: =cut
  534: 
  535: #########################################
  536: #########################################
  537: sub get_max_ids_indices {
  538:     my ($content)=@_;
  539:     my $maxindex=10;
  540:     my $maxid=10;
  541:     my $needsfixup=0;
  542:     my $duplicateids=0;
  543: 
  544:     my %allids;
  545:     my %duplicatedids;
  546: 
  547:     my $parser=HTML::LCParser->new($content);
  548:     $parser->xml_mode(1);
  549:     my $token;
  550:     while ($token=$parser->get_token) {
  551: 	if ($token->[0] eq 'S') {
  552: 	    my $counter;
  553: 	    if ($counter=$addid{$token->[1]}) {
  554: 		if ($counter eq 'id') {
  555: 		    if (defined($token->[2]->{'id'}) &&
  556: 			$token->[2]->{'id'} !~ /^\s*$/) {
  557: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
  558: 			if (exists($allids{$token->[2]->{'id'}})) {
  559: 			    $duplicateids=1;
  560: 			    $duplicatedids{$token->[2]->{'id'}}=1;
  561: 			} else {
  562: 			    $allids{$token->[2]->{'id'}}=1;
  563: 			}
  564: 		    } else {
  565: 			$needsfixup=1;
  566: 		    }
  567: 		} else {
  568: 		    if (defined($token->[2]->{'index'}) &&
  569: 			$token->[2]->{'index'} !~ /^\s*$/) {
  570: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
  571: 		    } else {
  572: 			$needsfixup=1;
  573: 		    }
  574: 		}
  575: 	    }
  576: 	}
  577:     }
  578:     return ($needsfixup,$maxid,$maxindex,$duplicateids,
  579: 	    (keys(%duplicatedids)));
  580: }
  581: 
  582: #########################################
  583: #########################################
  584: 
  585: =pod
  586: 
  587: =item B<get_all_text_unbalanced>
  588: 
  589: Currently undocumented    
  590: 
  591: =cut
  592: 
  593: #########################################
  594: #########################################
  595: sub get_all_text_unbalanced {
  596:     #there is a copy of this in lonxml.pm
  597:     my($tag,$pars)= @_;
  598:     my $token;
  599:     my $result='';
  600:     $tag='<'.$tag.'>';
  601:     while ($token = $$pars[-1]->get_token) {
  602: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  603: 	    $result.=$token->[1];
  604: 	} elsif ($token->[0] eq 'PI') {
  605: 	    $result.=$token->[2];
  606: 	} elsif ($token->[0] eq 'S') {
  607: 	    $result.=$token->[4];
  608: 	} elsif ($token->[0] eq 'E')  {
  609: 	    $result.=$token->[2];
  610: 	}
  611: 	if ($result =~ /\Q$tag\E/s) {
  612: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
  613: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
  614: 	    #&Apache::lonnet::logthis('Result is :'.$1);
  615: 	    $redo=$tag.$redo;
  616: 	    push (@$pars,HTML::LCParser->new(\$redo));
  617: 	    $$pars[-1]->xml_mode('1');
  618: 	    last;
  619: 	}
  620:     }
  621:     return $result
  622: }
  623: 
  624: #########################################
  625: #########################################
  626: 
  627: =pod
  628: 
  629: =item B<fix_ids_and_indices>
  630: 
  631: Currently undocumented    
  632: 
  633: =cut
  634: 
  635: #########################################
  636: #########################################
  637: #Arguably this should all be done as a lonnet::ssi instead
  638: sub fix_ids_and_indices {
  639:     my ($logfile,$source,$target)=@_;
  640: 
  641:     my %allow;
  642:     my $content;
  643:     {
  644: 	my $org=Apache::File->new($source);
  645: 	$content=join('',<$org>);
  646:     }
  647: 
  648:     my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
  649: 	&get_max_ids_indices(\$content);
  650: 
  651:     print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
  652: 			   join(', ',@duplicatedids));
  653:     if ($duplicateids) {
  654: 	print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
  655: 	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>';
  656: 	return ($outstring,1);
  657:     }
  658:     if ($needsfixup) {
  659: 	print $logfile "Needs ID and/or index fixup\n".
  660: 	    "Max ID   : $maxid (min 10)\n".
  661:                 "Max Index: $maxindex (min 10)\n";
  662:     }
  663:     my $outstring='';
  664:     my @parser;
  665:     $parser[0]=HTML::LCParser->new(\$content);
  666:     $parser[-1]->xml_mode(1);
  667:     my $token;
  668:     while (@parser) {
  669: 	while ($token=$parser[-1]->get_token) {
  670: 	    if ($token->[0] eq 'S') {
  671: 		my $counter;
  672: 		my $tag=$token->[1];
  673: 		my $lctag=lc($tag);
  674: 		if ($lctag eq 'allow') {
  675: 		    $allow{$token->[2]->{'src'}}=1;
  676: 		    next;
  677: 		}
  678: 		if ($lctag eq 'base') { next; }
  679: 		my %parms=%{$token->[2]};
  680: 		$counter=$addid{$tag};
  681: 		if (!$counter) { $counter=$addid{$lctag}; }
  682: 		if ($counter) {
  683: 		    if ($counter eq 'id') {
  684: 			unless (defined($parms{'id'}) &&
  685: 				$parms{'id'}!~/^\s*$/) {
  686: 			    $maxid++;
  687: 			    $parms{'id'}=$maxid;
  688: 			    print $logfile 'ID(new) : '.$tag.':'.$maxid."\n";
  689: 			} else {
  690: 			    print $logfile 'ID(kept): '.$tag.':'.$parms{'id'}."\n";
  691: 			}
  692: 		    } elsif ($counter eq 'index') {
  693: 			unless (defined($parms{'index'}) &&
  694: 				$parms{'index'}!~/^\s*$/) {
  695: 			    $maxindex++;
  696: 			    $parms{'index'}=$maxindex;
  697: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
  698: 			}
  699: 		    }
  700: 		}
  701:                 unless ($parms{'type'} eq 'zombie') {
  702: 		    foreach my $type ('src','href','background','bgimg') {
  703: 			foreach my $key (keys(%parms)) {
  704: 			    if ($key =~ /^$type$/i) {
  705: 				$parms{$key}=&set_allow(\%allow,$logfile,
  706: 							$target,$tag,
  707: 							$parms{$key});
  708: 			    }
  709: 			}
  710: 		    }
  711: 		}
  712: 		# probably a <randomlabel> image type <label>
  713: 		# or a <image> tag inside <imageresponse>
  714: 		if (($lctag eq 'label' && defined($parms{'description'}))
  715: 		    ||
  716: 		    ($lctag eq 'image')) {
  717: 		    my $next_token=$parser[-1]->get_token();
  718: 		    if ($next_token->[0] eq 'T') {
  719:                         $next_token->[1] =~ s/[\n\r\f]+//g;
  720: 			$next_token->[1]=&set_allow(\%allow,$logfile,
  721: 						    $target,$tag,
  722: 						    $next_token->[1]);
  723: 		    }
  724: 		    $parser[-1]->unget_token($next_token);
  725: 		}
  726: 		if ($lctag eq 'applet') {
  727: 		    my $codebase='';
  728: 		    my $havecodebase=0;
  729: 		    foreach my $key (keys(%parms)) {
  730: 			if (lc($key) eq 'codebase') { 
  731: 			    $codebase=$parms{$key};
  732: 			    $havecodebase=1; 
  733: 			}
  734: 		    }
  735: 		    if ($havecodebase) {
  736: 			my $oldcodebase=$codebase;
  737: 			unless ($oldcodebase=~/\/$/) {
  738: 			    $oldcodebase.='/';
  739: 			}
  740: 			$codebase=&urlfixup($oldcodebase,$target);
  741: 			$codebase=~s/\/$//;    
  742: 			if ($codebase ne $oldcodebase) {
  743: 			    $parms{'codebase'}=$codebase;
  744: 			    print $logfile 'URL codebase: '.$tag.':'.
  745: 				$oldcodebase.' - '.
  746: 				    $codebase."\n";
  747: 			}
  748: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
  749: 		    } else {
  750: 			foreach my $key (keys(%parms)) {
  751: 			    if ($key =~ /(archive|code|object)/i) {
  752: 				my $oldurl=$parms{$key};
  753: 				my $newurl=&urlfixup($oldurl,$target);
  754: 				$newurl=~s/\/[^\/]+$/\/\*/;
  755: 				print $logfile 'Allow: applet '.lc($key).':'.
  756: 				    $oldurl.' allows '.$newurl."\n";
  757: 				$allow{&absoluteurl($newurl,$target)}=1;
  758: 			    }
  759: 			}
  760: 		    }
  761: 		}
  762: 		my $newparmstring='';
  763: 		my $endtag='';
  764: 		foreach (keys %parms) {
  765: 		    if ($_ eq '/') {
  766: 			$endtag=' /';
  767: 		    } else { 
  768: 			my $quote=($parms{$_}=~/\"/?"'":'"');
  769: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
  770: 		    }
  771: 		}
  772: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  773: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
  774: 		if ($lctag eq 'm' || $lctag eq 'script' 
  775:                     || $lctag eq 'display' || $lctag eq 'tex') {
  776: 		    $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
  777: 		}
  778: 	    } elsif ($token->[0] eq 'E') {
  779: 		if ($token->[2]) {
  780: 		    unless ($token->[1] eq 'allow') {
  781: 			$outstring.='</'.$token->[1].'>';
  782: 		    }
  783: 		}
  784: 	    } else {
  785: 		$outstring.=$token->[1];
  786: 	    }
  787: 	}
  788: 	pop(@parser);
  789:     }
  790: 
  791:     if ($needsfixup) {
  792: 	print $logfile "End of ID and/or index fixup\n".
  793: 	    "Max ID   : $maxid (min 10)\n".
  794: 		"Max Index: $maxindex (min 10)\n";
  795:     } else {
  796: 	print $logfile "Does not need ID and/or index fixup\n";
  797:     }
  798: 
  799:     return ($outstring,0,%allow);
  800: }
  801: 
  802: #########################################
  803: #########################################
  804: 
  805: =pod
  806: 
  807: =item B<store_metadata>
  808: 
  809: Store the metadata in the metadata table in the loncapa database.
  810: Uses lonmysql to access the database.
  811: 
  812: Inputs: \%metadata
  813: 
  814: Returns: (error,status).  error is undef on success, status is undef on error.
  815: 
  816: =cut
  817: 
  818: #########################################
  819: #########################################
  820: sub store_metadata {
  821:     my %metadata = @_;
  822:     my $error;
  823:     # Determine if the table exists
  824:     my $status = &Apache::lonmysql::check_table('metadata');
  825:     if (! defined($status)) {
  826:         $error='<font color="red">WARNING: Cannot connect to '.
  827:             'database!</font>';
  828:         &Apache::lonnet::logthis($error);
  829:         return ($error,undef);
  830:     }
  831:     if ($status == 0) {
  832:         # It would be nice to actually create the table....
  833:         $error ='<font color="red">WARNING: The metadata table does not '.
  834:             'exist in the LON-CAPA database.</font>';
  835:         &Apache::lonnet::logthis($error);
  836:         return ($error,undef);
  837:     }
  838:     my $dbh = &Apache::lonmysql::get_dbh();
  839:     if (($metadata{'obsolete'}) || ($metadata{'copyright'} eq 'priv') ||
  840: 	($metadata{'copyright'} eq 'custom')) {
  841:         # remove this entry
  842: 	$status=&LONCAPA::lonmetadata::delete_metadata($dbh,undef,
  843:                                                        $metadata{'url'});
  844:     } else {
  845:         $status = &LONCAPA::lonmetadata::update_metadata($dbh,undef,undef,
  846:                                                          \%metadata);
  847:     }
  848:     if (defined($status) && $status ne '') {
  849:         $error='<font color="red">Error occured storing new values in '.
  850:             'metadata table in LON-CAPA database</font>';
  851:         &Apache::lonnet::logthis($error);
  852:         &Apache::lonnet::logthis($status);
  853:         return ($error,undef);
  854:     }
  855:     return (undef,'success');
  856: }
  857: 
  858: 
  859: # ========================================== Parse file for errors and warnings
  860: 
  861: sub checkonthis {
  862:     my ($r,$source)=@_;
  863:     my $uri=&Apache::lonnet::hreflocation($source);
  864:     $uri=~s/\/$//;
  865:     my $result=&Apache::lonnet::ssi_body($uri,
  866: 					 ('grade_target'=>'web',
  867: 					  'return_only_error_and_warning_counts' => 1));
  868:     my ($errorcount,$warningcount)=split(':',$result);
  869:     if (($errorcount) || ($warningcount)) {
  870:         $r->print('<br /><tt>'.$uri.'</tt>: ');
  871: 	if ($errorcount) {
  872: 	    $r->print('<img src="/adm/lonMisc/bomb.gif" /><font color="red"><b>'.
  873: 		      $errorcount.' '.
  874: 		      &mt('error(s)').'</b></font> ');
  875: 	}
  876: 	if ($warningcount) {
  877: 	    $r->print('<font color="blue">'.
  878: 		      $warningcount.' '.
  879: 		      &mt('warning(s)').'</font>');
  880: 	}
  881:     } else {
  882: 	#$r->print('<font color="green">'.&mt('ok').'</font>');
  883:     }
  884:     $r->rflush();
  885:     return ($warningcount,$errorcount);
  886: }
  887: 
  888: # ============================================== Parse file itself for metadata
  889: #
  890: # parses a file with target meta, sets global %metadatafields %metadatakeys 
  891: 
  892: sub parseformeta {
  893:     my ($source,$style)=@_;
  894:     my $allmeta='';
  895:     if (($style eq 'ssi') || ($style eq 'prv')) {
  896: 	my $dir=$source;
  897: 	$dir=~s-/[^/]*$--;
  898: 	my $file=$source;
  899: 	$file=(split('/',$file))[-1];
  900:         $source=&Apache::lonnet::hreflocation($dir,$file);
  901: 	$allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
  902:         &metaeval($allmeta);
  903:     }
  904:     return $allmeta;
  905: }
  906: 
  907: #########################################
  908: #########################################
  909: 
  910: =pod
  911: 
  912: =item B<publish>
  913: 
  914: This is the workhorse function of this module.  This subroutine generates
  915: backup copies, performs any automatic processing (prior to publication,
  916: especially for rat and ssi files),
  917: 
  918: Returns a 2 element array, the first is the string to be shown to the
  919: user, the second is an error code, either 1 (an error occured) or 0
  920: (no error occurred)
  921: 
  922: I<Additional documentation needed.>
  923: 
  924: =cut
  925: 
  926: #########################################
  927: #########################################
  928: sub publish {
  929: 
  930:     my ($source,$target,$style,$batch)=@_;
  931:     my $logfile;
  932:     my $scrout='';
  933:     my $allmeta='';
  934:     my $content='';
  935:     my %allow=();
  936: 
  937:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  938: 	return ('<font color="red">'.&mt('No write permission to user directory, FAIL').'</font>',1);
  939:     }
  940:     print $logfile 
  941: "\n\n================= Publish ".localtime()." Phase One  ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
  942: 
  943:     if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
  944: # ------------------------------------------------------- This needs processing
  945: 
  946: # ----------------------------------------------------------------- Backup Copy
  947: 	my $copyfile=$source.'.save';
  948:         if (copy($source,$copyfile)) {
  949: 	    print $logfile "Copied original file to ".$copyfile."\n";
  950:         } else {
  951: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
  952: 	    return ("<font color=\"red\">Failed to write backup copy, $!,FAIL</font>",1);
  953:         }
  954: # ------------------------------------------------------------- IDs and indices
  955: 	
  956: 	my ($outstring,$error);
  957: 	($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
  958: 							$target);
  959: 	if ($error) { return ($outstring,$error); }
  960: # ------------------------------------------------------------ Construct Allows
  961:     
  962: 	$scrout.='<h3>'.&mt('Dependencies').'</h3>';
  963:         my $allowstr='';
  964:         foreach (sort(keys(%allow))) {
  965: 	   my $thisdep=$_;
  966: 	   if ($thisdep !~ /[^\s]/) { next; }
  967:            unless ($style eq 'rat') { 
  968:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
  969: 	   }
  970:            $scrout.='<br />';
  971:            if ($thisdep!~/\*/ && $thisdep!~m|^/adm/|) {
  972: 	       $scrout.='<a href="'.$thisdep.'">';
  973:            }
  974:            $scrout.='<tt>'.$thisdep.'</tt>';
  975:            if ($thisdep!~/\*/ && $thisdep!~m|^/adm/|) {
  976: 	       $scrout.='</a>';
  977:                if (
  978:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
  979:                                             $thisdep.'.meta') eq '-1') {
  980: 		   $scrout.= ' - <font color="red">'.&mt('Currently not available').
  981: 		       '</font>';
  982:                } else {
  983:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
  984:                              &Apache::lonnet::declutter($thisdep).'___usage'
  985:                                  => time);
  986:                    $thisdep=~m{^/res/($match_domain)/($match_username)/};
  987:                    if ((defined($1)) && (defined($2))) {
  988:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
  989: 					   $1,$2);
  990: 		   }
  991: 	       }
  992:            }
  993:         }
  994:         $outstring=~s/\n*(\<\/[^\>]+\>[^<]*)$/$allowstr\n$1\n/s;
  995: 
  996: # ------------------------------------------------------------- Write modified.
  997: 
  998:         {
  999:           my $org;
 1000:           unless ($org=Apache::File->new('>'.$source)) {
 1001:              print $logfile "No write permit to $source\n";
 1002:              return ('<font color="red">'.&mt('No write permission to').
 1003: 		     ' '.$source.
 1004: 		     ', '.&mt('FAIL').'</font>',1);
 1005: 	  }
 1006:           print($org $outstring);
 1007:         }
 1008: 	  $content=$outstring;
 1009: 
 1010:     }
 1011: # -------------------------------------------- Initial step done, now metadata.
 1012: 
 1013: # --------------------------------------- Storage for metadata keys and fields.
 1014: # these are globals
 1015: #
 1016:      %metadatafields=();
 1017:      %metadatakeys=();
 1018:      
 1019:      my %oldparmstores=();
 1020:      
 1021:     unless ($batch) {
 1022:      $scrout.='<h3>'.&mt('Metadata Information').' ' .
 1023:        Apache::loncommon::help_open_topic("Metadata_Description")
 1024:        . '</h3>';
 1025:     }
 1026: 
 1027: # ------------------------------------------------ First, check out environment
 1028:      if ((!(-e $source.'.meta')) || ($env{'form.forceoverride'})) {
 1029:         $metadatafields{'author'}=$env{'environment.firstname'}.' '.
 1030: 	                          $env{'environment.middlename'}.' '.
 1031: 		                  $env{'environment.lastname'}.' '.
 1032: 		                  $env{'environment.generation'};
 1033:         $metadatafields{'author'}=~s/\s+/ /g;
 1034:         $metadatafields{'author'}=~s/\s+$//;
 1035:         $metadatafields{'owner'}=$cuname.':'.$cudom;
 1036: 
 1037: # ------------------------------------------------ Check out directory hierachy
 1038: 
 1039:         my $thisdisfn=$source;
 1040:         $thisdisfn=~s/^\/home\/\Q$cuname\E\///;
 1041: 
 1042:         my @urlparts=split(/\//,$thisdisfn);
 1043:         $#urlparts--;
 1044: 
 1045:         my $currentpath='/home/'.$cuname.'/';
 1046: 
 1047: 	my $prefix='../'x($#urlparts);
 1048:         foreach (@urlparts) {
 1049: 	    $currentpath.=$_.'/';
 1050:             $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
 1051: 	    $prefix=~s|^\.\./||;
 1052:         }
 1053: 
 1054: # ----------------------------------------------------------- Parse file itself
 1055: # read %metadatafields from file itself
 1056:  
 1057: 	$allmeta=&parseformeta($source,$style);
 1058: 
 1059: # ------------------- Clear out parameters and stores (there should not be any)
 1060: 
 1061:         foreach (keys %metadatafields) {
 1062: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
 1063: 		delete $metadatafields{$_};
 1064:             }
 1065:         }
 1066: 
 1067:     } else {
 1068: # ---------------------- Read previous metafile, remember parameters and stores
 1069: 
 1070:         $scrout.=&metaread($logfile,$source.'.meta');
 1071: 
 1072:         foreach (keys %metadatafields) {
 1073: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
 1074:                 $oldparmstores{$_}=1;
 1075: 		delete $metadatafields{$_};
 1076:             }
 1077:         }
 1078: # ------------------------------------------------------------- Save some stuff
 1079:         my %savemeta=();
 1080:         foreach ('title') {
 1081:             $savemeta{$_}=$metadatafields{$_};
 1082: 	}
 1083: # ------------------------------------------ See if anything new in file itself
 1084:  
 1085: 	$allmeta=&parseformeta($source,$style);
 1086: # ----------------------------------------------------------- Restore the stuff
 1087:         foreach (keys %savemeta) {
 1088: 	    $metadatafields{$_}=$savemeta{$_};
 1089: 	}
 1090:    }
 1091: 
 1092:        
 1093: # ---------------- Find and document discrepancies in the parameters and stores
 1094: 
 1095:     my $chparms='';
 1096:     foreach (sort keys %metadatafields) {
 1097: 	if (($_=~/^parameter/) || ($_=~/^stores/)) {
 1098: 	    unless ($_=~/\.\w+$/) { 
 1099: 		unless ($oldparmstores{$_}) {
 1100: 		    my $disp_key = $_;
 1101: 		    $disp_key =~ tr/\0/_/;
 1102: 		    print $logfile ('New: '.$disp_key."\n");
 1103: 		    $chparms .= $disp_key.' ';
 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: 		my $disp_key = $_;
 1119: 		$disp_key =~ tr/\0/_/;
 1120: 		print $logfile ('Obsolete: '.$disp_key."\n");
 1121: 		$chparms.=$disp_key.' ';
 1122: 	    }
 1123: 	}
 1124:     }
 1125:     if ($chparms) {
 1126: 	$scrout.='<p><b>'.&mt('Obsolete parameters or stored values').':</b> '.
 1127: 	    $chparms.'</p><h1><span class="LC_warning">'.&mt('Warning!').
 1128: 	    '</span></h1><p><span class="LC_warning">'.
 1129: 	    &mt('If this resource is in active use, student performance data from the previous version may become inaccessible.').'</span></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:     $metadatafields{'domain'}=$cudom;
 1474:     
 1475:     my $allkeywords=$env{'form.addkey'};
 1476:     if (exists($env{'form.keywords'})) {
 1477:         if (ref($env{'form.keywords'})) {
 1478:             $allkeywords .= ','.join(',',@{$env{'form.keywords'}});
 1479:         } else {
 1480:             $allkeywords .= ','.$env{'form.keywords'};
 1481:         }
 1482:     }
 1483:     $allkeywords=~s/[\"\']//g;
 1484:     $allkeywords=~s/\s*[\;\,]\s*/\,/g;
 1485:     $allkeywords=~s/\s+/ /g;
 1486:     $allkeywords=~s/^[ \,]//;
 1487:     $allkeywords=~s/[ \,]$//;
 1488:     $metadatafields{'keywords'}=$allkeywords;
 1489:     
 1490: # check if custom distribution file is specified
 1491:     if ($metadatafields{'copyright'} eq 'custom') {
 1492: 	my $file=$metadatafields{'customdistributionfile'};
 1493: 	unless ($file=~/\.rights$/) {
 1494:             $r->print(
 1495:                 '<font color="red">'.&mt('No valid custom distribution rights file specified, FAIL').
 1496: 		'</font>');
 1497: 	    return 0;
 1498:         }
 1499:     }
 1500:     {
 1501:         print $logfile "\nWrite metadata file for ".$source;
 1502:         my $mfh;
 1503:         unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
 1504:             $r->print( 
 1505:                 '<font color="red">'.&mt('Could not write metadata, FAIL').
 1506: 		'</font>');
 1507: 	    return 0;
 1508:         }
 1509:         foreach (sort keys %metadatafields) {
 1510:             unless ($_=~/\./) {
 1511:                 my $unikey=$_;
 1512:                 $unikey=~/^([A-Za-z]+)/;
 1513:                 my $tag=$1;
 1514:                 $tag=~tr/A-Z/a-z/;
 1515:                 print $mfh "\n\<$tag";
 1516:                 foreach (split(/\,/,$metadatakeys{$unikey})) {
 1517:                     my $value=$metadatafields{$unikey.'.'.$_};
 1518:                     $value=~s/\"/\'\'/g;
 1519:                     print $mfh ' '.$_.'="'.$value.'"';
 1520:                 }
 1521:                 print $mfh '>'.
 1522:                     &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
 1523:                         .'</'.$tag.'>';
 1524:             }
 1525:         }
 1526:         $r->print('<p>'.&mt('Wrote Metadata').'</p>');
 1527:         print $logfile "\nWrote metadata";
 1528:     }
 1529:     
 1530: # -------------------------------- Synchronize entry with SQL metadata database
 1531: 
 1532:     $metadatafields{'url'} = $distarget;
 1533:     $metadatafields{'version'} = 'current';
 1534: 
 1535:     my ($error,$success) = &store_metadata(%metadatafields);
 1536:     if ($success) {
 1537: 	$r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
 1538: 	print $logfile "\nSynchronized SQL metadata database";
 1539:     } else {
 1540: 	$r->print($error);
 1541: 	print $logfile "\n".$error;
 1542:     }
 1543: # --------------------------------------------- Delete author resource messages
 1544:     my $delresult=&Apache::lonmsg::del_url_author_res_msg($target); 
 1545:     $r->print('<p>'.&mt('Removing error messages:').' '.$delresult.'</p>');
 1546:     print $logfile "\nRemoving error messages: $delresult";
 1547: # ----------------------------------------------------------- Copy old versions
 1548:    
 1549:     if (-e $target) {
 1550:         my $filename;
 1551:         my $maxversion=0;
 1552:         $target=~/(.*)\/([^\/]+)\.(\w+)$/;
 1553:         my $srcf=$2;
 1554:         my $srct=$3;
 1555:         my $srcd=$1;
 1556:         unless ($srcd=~/^\/home\/httpd\/html\/res/) {
 1557:             print $logfile "\nPANIC: Target dir is ".$srcd;
 1558:             $r->print(
 1559: 	 "<font color=\"red\">Invalid target directory, FAIL</font>");
 1560: 	    return 0;
 1561:         }
 1562:         opendir(DIR,$srcd);
 1563:         while ($filename=readdir(DIR)) {
 1564:             if (-l $srcd.'/'.$filename) {
 1565:                 unlink($srcd.'/'.$filename);
 1566:                 unlink($srcd.'/'.$filename.'.meta');
 1567:             } else {
 1568:                 if ($filename=~/\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
 1569:                     $maxversion=($1>$maxversion)?$1:$maxversion;
 1570:                 }
 1571:             }
 1572:         }
 1573:         closedir(DIR);
 1574:         $maxversion++;
 1575:         $r->print('<p>Creating old version '.$maxversion.'</p>');
 1576:         print $logfile "\nCreating old version ".$maxversion."\n";
 1577:         
 1578:         my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
 1579:         
 1580:         if (copy($target,$copyfile)) {
 1581: 	    print $logfile "Copied old target to ".$copyfile."\n";
 1582:             $r->print('<p>'.&mt('Copied old target file').'</p>');
 1583:         } else {
 1584: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 1585:             $r->print("<font color=\"red\">".&mt('Failed to copy old target').
 1586: 		", $!, ".&mt('FAIL')."</font>");
 1587: 	    return 0;
 1588:         }
 1589:         
 1590: # --------------------------------------------------------------- Copy Metadata
 1591: 
 1592: 	$copyfile=$copyfile.'.meta';
 1593:         
 1594:         if (copy($target.'.meta',$copyfile)) {
 1595: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
 1596:             $r->print('<p>'.&mt('Copied old metadata').'</p>')
 1597:         } else {
 1598: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 1599:             if (-e $target.'.meta') {
 1600:                 $r->print( 
 1601:                     "<font color=\"red\">".
 1602: &mt('Failed to write old metadata copy').", $!, ".&mt('FAIL')."</font>");
 1603: 		return 0;
 1604: 	    }
 1605:         }
 1606:         
 1607:         
 1608:     } else {
 1609:         $r->print('<p>'.&mt('Initial version').'</p>');
 1610:         print $logfile "\nInitial version";
 1611:     }
 1612: 
 1613: # ---------------------------------------------------------------- Write Source
 1614:     my $copyfile=$target;
 1615:     
 1616:     my @parts=split(/\//,$copyfile);
 1617:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1618:     
 1619:     my $count;
 1620:     for ($count=5;$count<$#parts;$count++) {
 1621:         $path.="/$parts[$count]";
 1622:         if ((-e $path)!=1) {
 1623:             print $logfile "\nCreating directory ".$path;
 1624:             $r->print('<p>'.&mt('Created directory').' '.$parts[$count].'</p>');
 1625:             mkdir($path,0777);
 1626:         }
 1627:     }
 1628:     
 1629:     if (copy($source,$copyfile)) {
 1630:         print $logfile "\nCopied original source to ".$copyfile."\n";
 1631:         $r->print('<p>'.&mt('Copied source file').'</p>');
 1632:     } else {
 1633:         print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 1634:         $r->print("<font color=\"red\">".
 1635: 	    &mt('Failed to copy source').", $!, ".&mt('FAIL')."</font>");
 1636: 	return 0;
 1637:     }
 1638:     
 1639: # --------------------------------------------------------------- Copy Metadata
 1640: 
 1641:     $copyfile=$copyfile.'.meta';
 1642:     
 1643:     if (copy($source.'.meta',$copyfile)) {
 1644:         print $logfile "\nCopied original metadata to ".$copyfile."\n";
 1645:         $r->print('<p>'.&mt('Copied metadata').'</p>');
 1646:     } else {
 1647:         print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
 1648:         $r->print(
 1649:             "<font color=\"red\">".&mt('Failed to write metadata copy').", $!, ".&mt('FAIL')."</font>");
 1650: 	return 0;
 1651:     }
 1652:     $r->rflush;
 1653: 
 1654: # ------------------------------------------------------------- Trigger updates
 1655:     push(@{$modified_urls},[$target,$source]);
 1656:     unless ($registered_cleanup) {
 1657: 	$r->register_cleanup(\&notify);
 1658: 	$registered_cleanup=1;
 1659:     }
 1660: 
 1661: # ---------------------------------------------------------- Clear local caches
 1662:     my $thisdistarget=$target;
 1663:     $thisdistarget=~s/^\Q$docroot\E//;
 1664:     &Apache::lonnet::devalidate_cache_new('resversion',$target);
 1665:     &Apache::lonnet::devalidate_cache_new('meta',
 1666: 			 &Apache::lonnet::declutter($thisdistarget));
 1667: 
 1668: # ------------------------------------------------ Provide link to new resource
 1669:     unless ($batch) {
 1670:         
 1671:         my $thissrc=$source;
 1672:         $thissrc=~s{^/home/($match_username)/public_html}{/priv/$1};
 1673:         
 1674:         my $thissrcdir=$thissrc;
 1675:         $thissrcdir=~s/\/[^\/]+$/\//;
 1676:         
 1677:         
 1678:         $r->print(
 1679:            '<hr /><a href="'.$thisdistarget.'"><font size="+2">'.
 1680:            &mt('View Published Version').'</font></a>'.
 1681:            '<p><a href="'.$thissrc.'"><font size=+2>'.
 1682: 		  &mt('Back to Source').'</font></a></p>'.
 1683:            '<p><a href="'.$thissrcdir.
 1684:                    '"><font size="+2">'.
 1685: 		  &mt('Back to Source Directory').'</font></a></p>');
 1686:     }
 1687:     $logfile->close();
 1688:     $r->print('<p><font color="green">'.&mt('Done').'</font></p>');
 1689:     return 1;
 1690: }
 1691: 
 1692: # =============================================================== Notifications
 1693: sub notify {  
 1694: # --------------------------------------------------- Send update notifications
 1695:     foreach my $targetsource (@{$modified_urls}){
 1696: 	my ($target,$source)=@{$targetsource};
 1697: 	my $logfile=Apache::File->new('>>'.$source.'.log');
 1698: 	print $logfile "\nCleanup phase: Notifications\n";
 1699: 	my @subscribed=&get_subscribed_hosts($target);
 1700: 	foreach my $subhost (@subscribed) {
 1701: 	    print $logfile "\nNotifying host ".$subhost.':';
 1702: 	    my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 1703: 	    print $logfile $reply;
 1704: 	}
 1705: # ---------------------------------------- Send update notifications, meta only
 1706: 	my @subscribedmeta=&get_subscribed_hosts("$target.meta");
 1707: 	foreach my $subhost (@subscribedmeta) {
 1708: 	    print $logfile "\nNotifying host for metadata only ".$subhost.':';
 1709: 	    my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 1710: 						$subhost);
 1711: 	    print $logfile $reply;
 1712: 	} 
 1713: # --------------------------------------------------- Notify subscribed courses
 1714: 	my %courses=&coursedependencies($target);
 1715: 	my $now=time;
 1716: 	foreach (keys %courses) {
 1717: 	    print $logfile "\nNotifying course ".$_.':';
 1718: 	    my ($cdom,$cname)=split(/\_/,$_);
 1719: 	    my $reply=&Apache::lonnet::cput
 1720: 		('versionupdate',{$target => $now},$cdom,$cname);
 1721: 	    print $logfile $reply;
 1722: 	}
 1723: 	print $logfile "\n============ Done ============\n";
 1724: 	$logfile->close();
 1725:     }
 1726:     return OK;
 1727: }
 1728: 
 1729: #########################################
 1730: 
 1731: sub batchpublish {
 1732:     my ($r,$srcfile,$targetfile)=@_;
 1733:     #publication pollutes %env with form.* values
 1734:     my %oldenv=%env;
 1735:     $srcfile=~s/\/+/\//g;
 1736:     $targetfile=~s/\/+/\//g;
 1737:     my $thisdisfn=$srcfile;
 1738:     $thisdisfn=~s/\/home\/korte\/public_html\///;
 1739:     $srcfile=~s/\/+/\//g;
 1740: 
 1741:     my $docroot=$r->dir_config('lonDocRoot');
 1742:     my $thisdistarget=$targetfile;
 1743:     $thisdistarget=~s/^\Q$docroot\E//;
 1744: 
 1745: 
 1746:     %metadatafields=();
 1747:     %metadatakeys=();
 1748:     $srcfile=~/\.(\w+)$/;
 1749:     my $thistype=$1;
 1750: 
 1751: 
 1752:     my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 1753:      
 1754:     $r->print('<h2>'.&mt('Publishing').' <tt>'.$thisdisfn.'</tt></h2>');
 1755: 
 1756: # phase one takes
 1757: #  my ($source,$target,$style,$batch)=@_;
 1758:     my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
 1759:     $r->print('<p>'.$outstring.'</p>');
 1760: # phase two takes
 1761: # my ($source,$target,$style,$distarget,batch)=@_;
 1762: # $env{'form.allmeta'},$env{'form.title'},$env{'form.author'},...
 1763:     if (!$error) {
 1764: 	$r->print('<p>');
 1765: 	&phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
 1766: 	$r->print('</p>');
 1767:     }
 1768:     %env=%oldenv;
 1769:     return '';
 1770: }
 1771: 
 1772: #########################################
 1773: 
 1774: sub publishdirectory {
 1775:     my ($r,$fn,$thisdisfn)=@_;
 1776:     $fn=~s/\/+/\//g;
 1777:     $thisdisfn=~s/\/+/\//g;
 1778:     my $resdir=
 1779: 	$Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cudom.'/'.$cuname.'/'.
 1780: 	$thisdisfn;
 1781:     $r->print('<h1>'.&mt('Directory').' <tt>'.$thisdisfn.'</tt></h1>'.
 1782: 	      &mt('Target').': <tt>'.$resdir.'</tt><br />');
 1783: 
 1784:     my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
 1785:     unless ($env{'form.phase'} eq 'two') {
 1786: # ask user what they want
 1787:         $r->print('<form name="pubdirpref" method="post">'.
 1788: 		  &hiddenfield('phase','two').
 1789: 		  &hiddenfield('filename',$env{'form.filename'}).
 1790: 		  &checkbox('pubrec','include subdirectories').
 1791: 		  &checkbox('forcerepub','force republication of previously published files').
 1792:                   &checkbox('obsolete','make file(s) obsolete').
 1793: 		  &checkbox('forceoverride','force directory level catalog information over existing').
 1794: 		  '<br /><input type="submit" value="'.&mt('Publish Directory').'" /></form>');
 1795:     } else {
 1796: # actually publish things
 1797: 	opendir(DIR,$fn);
 1798: 	my @files=sort(readdir(DIR));
 1799: 	foreach my $filename (@files) {
 1800: 	    my ($cdev,$cino,$cmode,$cnlink,
 1801: 		$cuid,$cgid,$crdev,$csize,
 1802: 		$catime,$cmtime,$cctime,
 1803: 		$cblksize,$cblocks)=stat($fn.'/'.$filename);
 1804: 	    
 1805: 	    my $extension='';
 1806: 	    if ($filename=~/\.(\w+)$/) { $extension=$1; }
 1807: 	    if ($cmode&$dirptr) {
 1808: 		if (($filename!~/^\./) && ($env{'form.pubrec'})) {
 1809: 		    &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
 1810: 		}
 1811: 	    } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
 1812: 		     ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
 1813: # find out publication status and/or exiting metadata
 1814: 		my $publishthis=0;
 1815: 		if (-e $resdir.'/'.$filename) {
 1816: 		    my ($rdev,$rino,$rmode,$rnlink,
 1817: 			$ruid,$rgid,$rrdev,$rsize,
 1818: 			$ratime,$rmtime,$rctime,
 1819: 			$rblksize,$rblocks)=stat($resdir.'/'.$filename);
 1820: 		    if (($rmtime<$cmtime) || ($env{'form.forcerepub'})) {
 1821: # previously published, modified now
 1822: 			$publishthis=1;
 1823: 		    }
 1824: 		    my $meta_cmtime = (stat($fn.'/'.$filename.'.meta'))[9];
 1825: 		    my $meta_rmtime = (stat($resdir.'/'.$filename.'.meta'))[9];
 1826: 		    if ( $meta_rmtime<$meta_cmtime ) {
 1827: 			$publishthis=1;
 1828: 		    }
 1829: 		} else {
 1830: # never published
 1831: 		    $publishthis=1;
 1832: 		}
 1833: 		
 1834: 		if ($publishthis) {
 1835: 		    &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
 1836: 		} else {
 1837: 		    $r->print('<br />'.&mt('Skipping').' '.$filename.'<br />');
 1838: 		}
 1839: 		$r->rflush();
 1840: 	    }
 1841: 	}
 1842: 	closedir(DIR);
 1843:     }
 1844: }
 1845: 
 1846: #########################################
 1847: # publish a default.meta file
 1848: 
 1849: sub defaultmetapublish {
 1850:     my ($r,$fn,$cuname,$cudom)=@_;
 1851:     $fn=~s/^\/\~$cuname\//\/home\/$cuname\/public_html\//;
 1852:     unless (-e $fn) {
 1853:        return HTTP_NOT_FOUND;
 1854:     }
 1855:     my $target=$fn;
 1856:     $target=~s/^\/home\/$cuname\/public_html\//$Apache::lonnet::perlvar{'lonDocRoot'}\/res\/$cudom\/$cuname\//;
 1857: 
 1858: 
 1859:     &Apache::loncommon::content_type($r,'text/html');
 1860:     $r->send_http_header;
 1861: 
 1862:     $r->print(&Apache::loncommon::start_page('Catalog Information Publication'));
 1863: 
 1864: # ---------------------------------------------------------------- Write Source
 1865:     my $copyfile=$target;
 1866:     
 1867:     my @parts=split(/\//,$copyfile);
 1868:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1869:     
 1870:     my $count;
 1871:     for ($count=5;$count<$#parts;$count++) {
 1872:         $path.="/$parts[$count]";
 1873:         if ((-e $path)!=1) {
 1874:             $r->print('<p>'.&mt('Created directory').' '.$parts[$count].'</p>');
 1875:             mkdir($path,0777);
 1876:         }
 1877:     }
 1878:     
 1879:     if (copy($fn,$copyfile)) {
 1880:         $r->print('<p>'.&mt('Copied source file').'</p>');
 1881:     } else {
 1882:         return "<font color=\"red\">".
 1883: 	    &mt('Failed to copy source').", $!, ".&mt('FAIL')."</font>";
 1884:     }
 1885: 
 1886: # --------------------------------------------------- Send update notifications
 1887: 
 1888:     my @subscribed=&get_subscribed_hosts($target);
 1889:     foreach my $subhost (@subscribed) {
 1890: 	$r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
 1891: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 1892: 	$r->print($reply.'</p><br />');$r->rflush;
 1893:     }
 1894: # ------------------------------------------------------------------- Link back
 1895:     my $link=$fn;
 1896:     $link=~s/^\/home\/$cuname\/public_html\//\/priv\/$cuname\//;
 1897:     $r->print("<a href='$link'>".&mt('Back to Catalog Information').'</a>');
 1898:     $r->print(&Apache::loncommon::end_page());
 1899:     return OK;
 1900: }
 1901: #########################################
 1902: 
 1903: =pod
 1904: 
 1905: =item B<handler>
 1906: 
 1907: A basic outline of the handler subroutine follows.
 1908: 
 1909: =over 4
 1910: 
 1911: =item *
 1912: 
 1913: Get query string for limited number of parameters.
 1914: 
 1915: =item *
 1916: 
 1917: Check filename.
 1918: 
 1919: =item *
 1920: 
 1921: File is there and owned, init lookup tables.
 1922: 
 1923: =item *
 1924: 
 1925: Start page output.
 1926: 
 1927: =item *
 1928: 
 1929: Evaluate individual file, and then output information.
 1930: 
 1931: =item *
 1932: 
 1933: Publishing from $thisfn to $thistarget with $thisembstyle.
 1934: 
 1935: =back
 1936: 
 1937: =cut
 1938: 
 1939: #########################################
 1940: #########################################
 1941: sub handler {
 1942:     my $r=shift;
 1943: 
 1944:     if ($r->header_only) {
 1945: 	&Apache::loncommon::content_type($r,'text/html');
 1946: 	$r->send_http_header;
 1947: 	return OK;
 1948:     }
 1949: 
 1950: # Get query string for limited number of parameters
 1951: 
 1952:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1953:                                             ['filename']);
 1954: 
 1955: # -------------------------------------- Flag and buffer for registered cleanup
 1956:     $registered_cleanup=0;
 1957:     @{$modified_urls}=();
 1958: # -------------------------------------------------------------- Check filename
 1959: 
 1960:     my $fn=&unescape($env{'form.filename'});
 1961: 
 1962:     ($cuname,$cudom)=
 1963: 	&Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
 1964: 
 1965: # special publication: default.meta file
 1966:     if ($fn=~/\/default.meta$/) {
 1967: 	return &defaultmetapublish($r,$fn,$cuname,$cudom); 
 1968:     }
 1969:     $fn=~s/\.meta$//;
 1970:   
 1971:     unless ($fn) { 
 1972: 	$r->log_reason($cuname.' at '.$cudom.
 1973: 		       ' trying to publish empty filename', $r->filename); 
 1974: 	return HTTP_NOT_FOUND;
 1975:     } 
 1976: 
 1977:     unless (($cuname) && ($cudom)) {
 1978: 	$r->log_reason($cuname.' at '.$cudom.
 1979: 		       ' trying to publish file '.$env{'form.filename'}.
 1980: 		       ' ('.$fn.') - not authorized', 
 1981: 		       $r->filename); 
 1982: 	return HTTP_NOT_ACCEPTABLE;
 1983:     }
 1984: 
 1985:     my $home=&Apache::lonnet::homeserver($cuname,$cudom);
 1986:     my $allowed=0;
 1987:     my @ids=&Apache::lonnet::current_machine_ids();
 1988:     foreach my $id (@ids) { if ($id eq $home) { $allowed = 1; }  }
 1989:     unless ($allowed) {
 1990: 	$r->log_reason($cuname.' at '.$cudom.
 1991: 		       ' trying to publish file '.$env{'form.filename'}.
 1992: 		       ' ('.$fn.') - not homeserver ('.$home.')', 
 1993: 		       $r->filename); 
 1994: 	return HTTP_NOT_ACCEPTABLE;
 1995:     }
 1996: 
 1997:     $fn=~s{^http://[^/]+}{};
 1998:     $fn=~s{^/~($match_username)}{/home/$1/public_html};
 1999: 
 2000:     my $targetdir='';
 2001:     $docroot=$r->dir_config('lonDocRoot'); 
 2002:     if ($1 ne $cuname) {
 2003: 	$r->log_reason($cuname.' at '.$cudom.
 2004: 		       ' trying to publish unowned file '.
 2005: 		       $env{'form.filename'}.' ('.$fn.')', 
 2006: 		       $r->filename); 
 2007: 	return HTTP_NOT_ACCEPTABLE;
 2008:     } else {
 2009: 	$targetdir=$docroot.'/res/'.$cudom;
 2010:     }
 2011:                                  
 2012:   
 2013:     unless (-e $fn) { 
 2014: 	$r->log_reason($cuname.' at '.$cudom.
 2015: 		       ' trying to publish non-existing file '.
 2016: 		       $env{'form.filename'}.' ('.$fn.')', 
 2017: 		       $r->filename); 
 2018: 	return HTTP_NOT_FOUND;
 2019:     } 
 2020: 
 2021: # -------------------------------- File is there and owned, init lookup tables.
 2022: 
 2023:     %addid=();
 2024:     
 2025:     {
 2026: 	my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
 2027: 	while (<$fh>=~/(\w+)\s+(\w+)/) {
 2028: 	    $addid{$1}=$2;
 2029: 	}
 2030:     }
 2031: 
 2032:     %nokey=();
 2033: 
 2034:     {
 2035: 	my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
 2036: 	while (<$fh>) {
 2037: 	    my $word=$_;
 2038: 	    chomp($word);
 2039: 	    $nokey{$word}=1;
 2040: 	}
 2041:     }
 2042: 
 2043: # ---------------------------------------------------------- Start page output.
 2044: 
 2045:     &Apache::loncommon::content_type($r,'text/html');
 2046:     $r->send_http_header;
 2047:     
 2048:     my $js='<script type="text/javascript">'.
 2049: 	&Apache::loncommon::browser_and_searcher_javascript().
 2050: 	'</script>';
 2051:     $r->print(&Apache::loncommon::start_page('Resource Publication',$js));
 2052: 
 2053: 
 2054:     my $thisfn=$fn;
 2055: 
 2056:     my $thistarget=$thisfn;
 2057:       
 2058:     $thistarget=~s/^\/home/$targetdir/;
 2059:     $thistarget=~s/\/public\_html//;
 2060: 
 2061:     my $thisdistarget=$thistarget;
 2062:     $thisdistarget=~s/^\Q$docroot\E//;
 2063: 
 2064:     my $thisdisfn=$thisfn;
 2065:     $thisdisfn=~s/^\/home\/\Q$cuname\E\/public_html\///;
 2066: 
 2067:     if ($fn=~/\/$/) {
 2068: # -------------------------------------------------------- This is a directory
 2069: 	&publishdirectory($r,$fn,$thisdisfn);
 2070: 	$r->print('<hr /><a href="/priv/'
 2071: 		  .$cuname.'/'.$thisdisfn
 2072: 		  .'">'.&mt('Return to Directory').'</a>');
 2073: 
 2074: 
 2075:     } else {
 2076: # ---------------------- Evaluate individual file, and then output information.
 2077: 	$thisfn=~/\.(\w+)$/;
 2078: 	my $thistype=$1;
 2079: 	my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 2080:         if ($thistype eq 'page') {  $thisembstyle = 'rat'; }
 2081: 	$r->print('<h2>'.&mt('Publishing').' '.
 2082: 		  &Apache::loncommon::filedescription($thistype).' <tt>');
 2083: 
 2084: 	$r->print(<<ENDCAPTION);
 2085: <a href='javascript:void(window.open("/~$cuname/$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
 2086: $thisdisfn</a>
 2087: ENDCAPTION
 2088:         $r->print('</tt></h2><b>'.&mt('Target').':</b> <tt>'.
 2089: 		  $thisdistarget.'</tt><br />');
 2090:    
 2091: 	if (($cuname ne $env{'user.name'})||($cudom ne $env{'user.domain'})) {
 2092: 	    $r->print('<h3><font color="red">'.&mt('Co-Author').': '.
 2093: 		      $cuname.&mt(' at ').$cudom.'</font></h3>');
 2094: 	}
 2095: 
 2096: 	if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
 2097: 	    $r->print(<<ENDDIFF);
 2098: <br />
 2099: <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"))'>
 2100: ENDDIFF
 2101:             $r->print(&mt('Diffs with Current Version').'</a><br />');
 2102: 	}
 2103:   
 2104: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
 2105: 
 2106: 	unless ($env{'form.phase'} eq 'two') {
 2107: # ---------------------------------------------------------- Parse for problems
 2108: 	    my ($warningcount,$errorcount);
 2109: 	    if ($thisembstyle eq 'ssi') {
 2110: 		($warningcount,$errorcount)=&checkonthis($r,$thisfn);
 2111: 	    }
 2112: 	    unless ($errorcount) {
 2113: 		my ($outstring,$error)=
 2114: 		    &publish($thisfn,$thistarget,$thisembstyle);
 2115: 		$r->print('<hr />'.$outstring);
 2116: 	    } else {
 2117: 		$r->print('<h3>'.
 2118: 			  &mt('The document contains errors and cannot be published.').
 2119: 			  '</h3>');
 2120: 	    }
 2121: 	} else {
 2122: 	    &phasetwo($r,$thisfn,$thistarget,$thisembstyle,$thisdistarget); 
 2123: 	    $r->print('<hr />');
 2124: 	}
 2125:     }
 2126:     $r->print(&Apache::loncommon::end_page());
 2127: 
 2128:     return OK;
 2129: }
 2130: 
 2131: 1;
 2132: __END__
 2133: 
 2134: =pod
 2135: 
 2136: =back
 2137: 
 2138: =back
 2139: 
 2140: =cut
 2141: 

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