File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.233: download - view: text, annotated - select for diffs
Mon May 12 20:59:22 2008 UTC (16 years ago) by www
Branches: MAIN
CVS tags: HEAD
Work on locks.

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

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