File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.219: download - view: text, annotated - select for diffs
Thu Feb 1 02:38:05 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- since _ is valid in metadata tags now, need to use a different temp
  separator in the return from &metaeval, switch to using \0 for this

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

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