File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.237: download - view: text, annotated - select for diffs
Wed May 28 22:22:35 2008 UTC (16 years ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #4106: really evaluate custom rights

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

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