File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.245: download - view: text, annotated - select for diffs
Thu Aug 14 13:39:02 2008 UTC (15 years, 9 months ago) by onken
Branches: MAIN
CVS tags: HEAD
this is a work simplification for german authors for present.

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

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