File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.242: download - view: text, annotated - select for diffs
Fri Aug 1 17:29:57 2008 UTC (15 years, 10 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Optimized display of warnings and errors
  - Added headline
  - Use LON-CAPA standard style
  - output as list instead of one after the other
  - optimized &mt() usage
  - Changed order: first warnings, then errors

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

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