Annotation of loncom/publisher/lonpublisher.pm, revision 1.140

1.1       www         1: # The LearningOnline Network with CAPA
                      2: # Publication Handler
1.54      albertel    3: #
1.140   ! albertel    4: # $Id: lonpublisher.pm,v 1.139 2003/10/21 19:50:15 albertel Exp $
1.54      albertel    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: #
1.1       www        28: # 
                     29: # (TeX Content Handler
                     30: #
                     31: # 05/29/00,05/30,10/11 Gerd Kortemeyer)
                     32: #
1.15      www        33: # 11/28,11/29,11/30,12/01,12/02,12/04,12/23 Gerd Kortemeyer
1.20      www        34: # 03/23 Guy Albertelli
1.23      www        35: # 03/24,03/29,04/03 Gerd Kortemeyer
1.27      www        36: # 05/03,05/05,05/07 Gerd Kortemeyer
1.51      www        37: # 06/23,08/07,08/11,8/13,8/17,8/18,8/24,9/26,10/16 Gerd Kortemeyer
1.58      www        38: # 12/04,12/05 Guy Albertelli
                     39: # 12/05 Gerd Kortemeyer
1.62      www        40: # 12/05 Guy Albertelli
1.64      www        41: # 12/06,12/07 Gerd Kortemeyer
1.67      www        42: # 12/25 Gerd Kortemeyer
1.71      www        43: # YEAR=2002
                     44: # 1/17 Gerd Kortemeyer
1.65      harris41   45: #
                     46: ###
                     47: 
                     48: ###############################################################################
                     49: ##                                                                           ##
                     50: ## ORGANIZATION OF THIS PERL MODULE                                          ##
                     51: ##                                                                           ##
                     52: ## 1. Modules used by this module                                            ##
                     53: ## 2. Various subroutines                                                    ##
                     54: ## 3. Publication Step One                                                   ##
                     55: ## 4. Phase Two                                                              ##
                     56: ## 5. Main Handler                                                           ##
                     57: ##                                                                           ##
                     58: ###############################################################################
1.1       www        59: 
1.90      matthew    60: 
                     61: ######################################################################
                     62: ######################################################################
                     63: 
                     64: =pod 
                     65: 
1.94      harris41   66: =head1 NAME
1.90      matthew    67: 
                     68: lonpublisher - LON-CAPA publishing handler
                     69: 
1.94      harris41   70: =head1 SYNOPSIS
1.90      matthew    71: 
1.94      harris41   72: B<lonpublisher> is used by B<mod_perl> inside B<Apache>.  This is the
                     73: invocation by F<loncapa_apache.conf>:
                     74: 
                     75:   <Location /adm/publish>
                     76:   PerlAccessHandler       Apache::lonacc
                     77:   SetHandler perl-script
                     78:   PerlHandler Apache::lonpublisher
                     79:   ErrorDocument     403 /adm/login
                     80:   ErrorDocument     404 /adm/notfound.html
                     81:   ErrorDocument     406 /adm/unauthorized.html
                     82:   ErrorDocument     500 /adm/errorhandler
                     83:   </Location>
1.127     bowersj2   84: 
                     85: =head1 OVERVIEW
                     86: 
                     87: Authors can only write-access the C</~authorname/> space. They can
                     88: copy resources into the resource area through the publication step,
                     89: and move them back through a recover step. Authors do not have direct
                     90: write-access to their resource space.
                     91: 
                     92: During the publication step, several events will be
                     93: triggered. Metadata is gathered, where a wizard manages default
                     94: entries on a hierarchical per-directory base: The wizard imports the
                     95: metadata (including access privileges and royalty information) from
                     96: the most recent published resource in the current directory, and if
                     97: that is not available, from the next directory above, etc. The Network
                     98: keeps all previous versions of a resource and makes them available by
                     99: an explicit version number, which is inserted between the file name
                    100: and extension, for example C<foo.2.html>, while the most recent
                    101: version does not carry a version number (C<foo.html>). Servers
                    102: subscribing to a changed resource are notified that a new version is
                    103: available.
1.94      harris41  104: 
                    105: =head1 DESCRIPTION
                    106: 
                    107: B<lonpublisher> takes the proper steps to add resources to the LON-CAPA
1.90      matthew   108: digital library.  This includes updating the metadata table in the
                    109: LON-CAPA database.
                    110: 
1.94      harris41  111: B<lonpublisher> is many things to many people.  
1.90      matthew   112: 
                    113: This module publishes a file.  This involves gathering metadata,
                    114: versioning the file, copying file from construction space to
                    115: publication space, and copying metadata from construction space
                    116: to publication space.
                    117: 
1.94      harris41  118: =head2 SUBROUTINES
                    119: 
                    120: Many of the undocumented subroutines implement various magical
                    121: parsing shortcuts.
1.90      matthew   122: 
                    123: =over 4
                    124: 
                    125: =cut
                    126: 
                    127: ######################################################################
                    128: ######################################################################
                    129: 
                    130: 
1.1       www       131: package Apache::lonpublisher;
                    132: 
1.65      harris41  133: # ------------------------------------------------- modules used by this module
1.1       www       134: use strict;
                    135: use Apache::File;
1.13      www       136: use File::Copy;
1.2       www       137: use Apache::Constants qw(:common :http :methods);
1.76      albertel  138: use HTML::LCParser;
1.4       www       139: use Apache::lonxml;
1.27      www       140: use Apache::loncacc;
1.24      harris41  141: use DBI;
1.65      harris41  142: use Apache::lonnet();
                    143: use Apache::loncommon();
1.89      matthew   144: use Apache::lonmysql;
1.134     www       145: use Apache::lonlocal;
1.105     www       146: use vars qw(%metadatafields %metadatakeys);
1.2       www       147: 
1.3       www       148: my %addid;
1.5       www       149: my %nokey;
1.10      www       150: 
1.12      www       151: my $docroot;
                    152: 
1.27      www       153: my $cuname;
                    154: my $cudom;
                    155: 
1.90      matthew   156: =pod
                    157: 
1.94      harris41  158: =item B<metaeval>
                    159: 
                    160: Evaluates a string that contains metadata.  This subroutine
                    161: stores values inside I<%metadatafields> and I<%metadatakeys>.
                    162: The hash key is a I<$unikey> corresponding to a unique id
                    163: that is descriptive of the parser location inside the XML tree.
                    164: 
                    165: Parameters:
                    166: 
                    167: =over 4
1.90      matthew   168: 
1.94      harris41  169: =item I<$metastring>
                    170: 
                    171: A string that contains metadata.
                    172: 
                    173: =back
                    174: 
                    175: Returns:
                    176: 
                    177: nothing
1.90      matthew   178: 
                    179: =cut
                    180: 
                    181: #########################################
                    182: #########################################
1.7       www       183: sub metaeval {
1.140   ! albertel  184:     my ($metastring,$prefix)=@_;
1.7       www       185:    
1.139     albertel  186:     my $parser=HTML::LCParser->new(\$metastring);
                    187:     my $token;
                    188:     while ($token=$parser->get_token) {
                    189: 	if ($token->[0] eq 'S') {
                    190: 	    my $entry=$token->[1];
                    191: 	    my $unikey=$entry;
                    192: 	    if (defined($token->[2]->{'package'})) { 
                    193: 		$unikey.='_package_'.$token->[2]->{'package'};
                    194: 	    } 
                    195: 	    if (defined($token->[2]->{'part'})) { 
                    196: 		$unikey.='_'.$token->[2]->{'part'}; 
                    197: 	    }
                    198: 	    if (defined($token->[2]->{'id'})) { 
                    199: 		$unikey.='_'.$token->[2]->{'id'};
                    200: 	    } 
                    201: 	    if (defined($token->[2]->{'name'})) { 
                    202: 		$unikey.='_'.$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: 	    }
1.140   ! albertel  212: 	    my $newentry=$parser->get_text('/'.$entry);
        !           213: 	    if ($entry eq 'customdistributionfile') {
        !           214: 		$newentry=~s/^\s*//;
        !           215: 		if ($newentry !~m|^/res|) { $newentry=$prefix.$newentry; }
        !           216: 	    }
1.139     albertel  217: 	    if ($metadatafields{$unikey}) {
                    218: 		unless (($metadatafields{$unikey}=~/\Q$newentry\E/) ||
                    219: 			($newentry eq '')) {
                    220: 		    $metadatafields{$unikey}.=', '.$newentry;
                    221: 		}
                    222: 	    } else {
1.140   ! albertel  223: 		$metadatafields{$unikey}=$newentry;
1.139     albertel  224: 	    }
                    225: 	}
                    226:     }
1.7       www       227: }
                    228: 
1.90      matthew   229: #########################################
                    230: #########################################
                    231: 
                    232: =pod
                    233: 
1.94      harris41  234: =item B<metaread>
1.90      matthew   235: 
                    236: Read a metadata file
                    237: 
1.94      harris41  238: Parameters:
                    239: 
                    240: =over
                    241: 
                    242: =item I<$logfile>
                    243: 
                    244: File output stream to output errors and warnings to.
                    245: 
                    246: =item I<$fn>
                    247: 
                    248: File name (including path).
                    249: 
                    250: =back
                    251: 
                    252: Returns:
                    253: 
                    254: =over 4
                    255: 
                    256: =item Scalar string (if successful)
                    257: 
                    258: XHTML text that indicates successful reading of the metadata.
                    259: 
                    260: =back
                    261: 
1.90      matthew   262: =cut
                    263: 
                    264: #########################################
                    265: #########################################
1.7       www       266: sub metaread {
1.140   ! albertel  267:     my ($logfile,$fn,$prefix)=@_;
1.7       www       268:     unless (-e $fn) {
1.94      harris41  269: 	print($logfile 'No file '.$fn."\n");
1.120     albertel  270:         return '<br /><b>No file:</b> <tt>'.$fn.'</tt>';
1.7       www       271:     }
1.94      harris41  272:     print($logfile 'Processing '.$fn."\n");
1.7       www       273:     my $metastring;
                    274:     {
1.140   ! albertel  275: 	my $metafh=Apache::File->new($fn);
        !           276: 	$metastring=join('',<$metafh>);
1.7       www       277:     }
1.140   ! albertel  278:     &metaeval($metastring,$prefix);
1.120     albertel  279:     return '<br /><b>Processed file:</b> <tt>'.$fn.'</tt>';
1.7       www       280: }
1.12      www       281: 
1.90      matthew   282: #########################################
                    283: #########################################
                    284: 
1.101     www       285: sub coursedependencies {
                    286:     my $url=&Apache::lonnet::declutter(shift);
                    287:     $url=~s/\.meta$//;
                    288:     my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
                    289:     my $regexp=$url;
                    290:     $regexp=~s/(\W)/\\$1/g;
                    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: 
1.90      matthew   306: =pod
                    307: 
1.94      harris41  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).
1.90      matthew   315: 
                    316: =over 4
                    317: 
1.94      harris41  318: =item B<textfield>
1.90      matthew   319: 
1.94      harris41  320: =item B<hiddenfield>
1.90      matthew   321: 
1.94      harris41  322: =item B<selectbox>
1.90      matthew   323: 
                    324: =back
                    325: 
                    326: =cut
                    327: 
                    328: #########################################
                    329: #########################################
1.8       www       330: sub textfield {
1.10      www       331:     my ($title,$name,$value)=@_;
1.134     www       332:     $title=&mt($title);
1.123     albertel  333:     my $uctitle=uc($title);
                    334:     return "\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
                    335:            "</b></font></p><br />".
1.94      harris41  336:            '<input type="text" name="'.$name.'" size=80 value="'.$value.'" />';
1.11      www       337: }
                    338: 
                    339: sub hiddenfield {
                    340:     my ($name,$value)=@_;
1.94      harris41  341:     return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
1.8       www       342: }
                    343: 
1.9       www       344: sub selectbox {
1.65      harris41  345:     my ($title,$name,$value,$functionref,@idlist)=@_;
1.134     www       346:     $title=&mt($title);
1.65      harris41  347:     my $uctitle=uc($title);
1.123     albertel  348:     $value=(split(/\s*,\s*/,$value))[-1];
1.65      harris41  349:     my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
1.123     albertel  350: 	'</b></font></p><br /><select name="'.$name.'">';
1.65      harris41  351:     foreach (@idlist) {
                    352:         $selout.='<option value=\''.$_.'\'';
                    353:         if ($_ eq $value) {
                    354: 	    $selout.=' selected>'.&{$functionref}($_).'</option>';
                    355: 	}
                    356:         else {$selout.='>'.&{$functionref}($_).'</option>';}
                    357:     }
1.10      www       358:     return $selout.'</select>';
1.9       www       359: }
                    360: 
1.90      matthew   361: #########################################
                    362: #########################################
                    363: 
                    364: =pod
                    365: 
1.94      harris41  366: =item B<urlfixup>
1.90      matthew   367: 
                    368: Fix up a url?  First step of publication
1.12      www       369: 
1.90      matthew   370: =cut
                    371: 
                    372: #########################################
                    373: #########################################
1.34      www       374: sub urlfixup {
1.35      www       375:     my ($url,$target)=@_;
1.39      www       376:     unless ($url) { return ''; }
1.68      albertel  377:     #javascript code needs no fixing
                    378:     if ($url =~ /^javascript:/i) { return $url; }
1.69      albertel  379:     if ($url =~ /^mailto:/i) { return $url; }
1.68      albertel  380:     #internal document links need no fixing
                    381:     if ($url =~ /^\#/) { return $url; } 
1.35      www       382:     my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
1.65      harris41  383:     foreach (values %Apache::lonnet::hostname) {
1.35      www       384: 	if ($_ eq $host) {
                    385: 	    $url=~s/^http\:\/\///;
                    386:             $url=~s/^$host//;
                    387:         }
1.65      harris41  388:     }
1.40      www       389:     if ($url=~/^http\:\/\//) { return $url; }
1.35      www       390:     $url=~s/\~$cuname/res\/$cudom\/$cuname/;
1.71      www       391:     return $url;
                    392: }
                    393: 
1.90      matthew   394: #########################################
                    395: #########################################
                    396: 
                    397: =pod
                    398: 
1.94      harris41  399: =item B<absoluteurl>
1.90      matthew   400: 
1.94      harris41  401: Currently undocumented.
1.90      matthew   402: 
                    403: =cut
1.71      www       404: 
1.90      matthew   405: #########################################
                    406: #########################################
1.71      www       407: sub absoluteurl {
                    408:     my ($url,$target)=@_;
                    409:     unless ($url) { return ''; }
1.35      www       410:     if ($target) {
                    411: 	$target=~s/\/[^\/]+$//;
                    412:        $url=&Apache::lonnet::hreflocation($target,$url);
                    413:     }
                    414:     return $url;
1.34      www       415: }
                    416: 
1.90      matthew   417: #########################################
                    418: #########################################
                    419: 
                    420: =pod
                    421: 
1.94      harris41  422: =item B<set_allow>
1.90      matthew   423: 
                    424: Currently undocumented    
                    425: 
                    426: =cut
                    427: 
                    428: #########################################
                    429: #########################################
1.81      albertel  430: sub set_allow {
                    431:     my ($allow,$logfile,$target,$tag,$oldurl)=@_;
                    432:     my $newurl=&urlfixup($oldurl,$target);
                    433:     my $return_url=$oldurl;
                    434:     print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
                    435:     if ($newurl ne $oldurl) {
                    436: 	$return_url=$newurl;
                    437: 	print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
                    438:     }
                    439:     if (($newurl !~ /^javascript:/i) &&
                    440: 	($newurl !~ /^mailto:/i) &&
                    441: 	($newurl !~ /^http:/i) &&
                    442: 	($newurl !~ /^\#/)) {
                    443: 	$$allow{&absoluteurl($newurl,$target)}=1;
                    444:     }
                    445:     return $return_url
                    446: }
                    447: 
1.90      matthew   448: #########################################
                    449: #########################################
                    450: 
                    451: =pod
                    452: 
1.94      harris41  453: =item B<get_subscribed_hosts>
1.90      matthew   454: 
                    455: Currently undocumented    
                    456: 
                    457: =cut
                    458: 
                    459: #########################################
                    460: #########################################
1.85      albertel  461: sub get_subscribed_hosts {
                    462:     my ($target)=@_;
                    463:     my @subscribed;
                    464:     my $filename;
                    465:     $target=~/(.*)\/([^\/]+)$/;
                    466:     my $srcf=$2;
                    467:     opendir(DIR,$1);
                    468:     while ($filename=readdir(DIR)) {
1.118     albertel  469: 	if ($filename=~/\Q$srcf\E\.(\w+)$/) {
1.85      albertel  470: 	    my $subhost=$1;
1.98      www       471: 	    if (($subhost ne 'meta' && $subhost ne 'subscription') &&
                    472:                 ($subhost ne $Apache::lonnet::perlvar{'lonHostID'})) {
1.85      albertel  473: 		push(@subscribed,$subhost);
                    474: 	    }
                    475: 	}
                    476:     }
                    477:     closedir(DIR);
                    478:     my $sh;
                    479:     if ( $sh=Apache::File->new("$target.subscription") ) {
                    480: 	&Apache::lonnet::logthis("opened $target.subscription");
                    481: 	while (my $subline=<$sh>) {
                    482: 	    &Apache::lonnet::logthis("Trying $subline");
1.98      www       483: 	    if ($subline =~ /(^\w+):/) { 
                    484:                 if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) { 
                    485:                    push(@subscribed,$1);
                    486: 	        }
                    487:             } else {
1.85      albertel  488: 		&Apache::lonnet::logthis("No Match for $subline");
                    489: 	    }
                    490: 	}
                    491:     } else {
1.94      harris41  492: 	&Apache::lonnet::logthis("Unable to open $target.subscription");
1.85      albertel  493:     }
                    494:     return @subscribed;
                    495: }
                    496: 
1.86      albertel  497: 
1.90      matthew   498: #########################################
                    499: #########################################
                    500: 
                    501: =pod
                    502: 
1.94      harris41  503: =item B<get_max_ids_indices>
1.90      matthew   504: 
                    505: Currently undocumented    
                    506: 
                    507: =cut
                    508: 
                    509: #########################################
                    510: #########################################
1.86      albertel  511: sub get_max_ids_indices {
                    512:     my ($content)=@_;
                    513:     my $maxindex=10;
                    514:     my $maxid=10;
                    515:     my $needsfixup=0;
1.106     albertel  516:     my $duplicateids=0;
                    517: 
                    518:     my %allids;
                    519:     my %duplicatedids;
1.86      albertel  520: 
                    521:     my $parser=HTML::LCParser->new($content);
                    522:     my $token;
                    523:     while ($token=$parser->get_token) {
                    524: 	if ($token->[0] eq 'S') {
                    525: 	    my $counter;
                    526: 	    if ($counter=$addid{$token->[1]}) {
                    527: 		if ($counter eq 'id') {
                    528: 		    if (defined($token->[2]->{'id'})) {
                    529: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
1.106     albertel  530: 			if (exists($allids{$token->[2]->{'id'}})) {
                    531: 			    $duplicateids=1;
                    532: 			    $duplicatedids{$token->[2]->{'id'}}=1;
                    533: 			} else {
                    534: 			    $allids{$token->[2]->{'id'}}=1;
                    535: 			}
1.86      albertel  536: 		    } else {
                    537: 			$needsfixup=1;
                    538: 		    }
                    539: 		} else {
                    540: 		    if (defined($token->[2]->{'index'})) {
                    541: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
                    542: 		    } else {
                    543: 			$needsfixup=1;
                    544: 		    }
                    545: 		}
                    546: 	    }
                    547: 	}
                    548:     }
1.106     albertel  549:     return ($needsfixup,$maxid,$maxindex,$duplicateids,
                    550: 	    (keys(%duplicatedids)));
1.86      albertel  551: }
                    552: 
1.90      matthew   553: #########################################
                    554: #########################################
                    555: 
                    556: =pod
                    557: 
1.94      harris41  558: =item B<get_all_text_unbalanced>
1.90      matthew   559: 
                    560: Currently undocumented    
                    561: 
                    562: =cut
                    563: 
                    564: #########################################
                    565: #########################################
1.87      albertel  566: sub get_all_text_unbalanced {
                    567:     #there is a copy of this in lonxml.pm
                    568:     my($tag,$pars)= @_;
                    569:     my $token;
                    570:     my $result='';
                    571:     $tag='<'.$tag.'>';
                    572:     while ($token = $$pars[-1]->get_token) {
                    573: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
                    574: 	    $result.=$token->[1];
                    575: 	} elsif ($token->[0] eq 'PI') {
                    576: 	    $result.=$token->[2];
                    577: 	} elsif ($token->[0] eq 'S') {
                    578: 	    $result.=$token->[4];
                    579: 	} elsif ($token->[0] eq 'E')  {
                    580: 	    $result.=$token->[2];
                    581: 	}
1.107     albertel  582: 	if ($result =~ /(.*)\Q$tag\E(.*)/s) {
1.88      albertel  583: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
                    584: 	    #&Apache::lonnet::logthis('Result is :'.$1);
1.87      albertel  585: 	    $result=$1;
                    586: 	    my $redo=$tag.$2;
                    587: 	    push (@$pars,HTML::LCParser->new(\$redo));
                    588: 	    $$pars[-1]->xml_mode('1');
                    589: 	    last;
                    590: 	}
                    591:     }
                    592:     return $result
                    593: }
                    594: 
1.90      matthew   595: #########################################
                    596: #########################################
                    597: 
                    598: =pod
                    599: 
1.94      harris41  600: =item B<fix_ids_and_indices>
1.90      matthew   601: 
                    602: Currently undocumented    
                    603: 
                    604: =cut
                    605: 
                    606: #########################################
                    607: #########################################
1.87      albertel  608: #Arguably this should all be done as a lonnet::ssi instead
1.86      albertel  609: sub fix_ids_and_indices {
                    610:     my ($logfile,$source,$target)=@_;
                    611: 
                    612:     my %allow;
                    613:     my $content;
                    614:     {
                    615: 	my $org=Apache::File->new($source);
                    616: 	$content=join('',<$org>);
                    617:     }
                    618: 
1.106     albertel  619:     my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
                    620: 	&get_max_ids_indices(\$content);
1.86      albertel  621: 
1.106     albertel  622:     print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
                    623: 			   join(', ',@duplicatedids));
                    624:     if ($duplicateids) {
                    625: 	print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
                    626: 	my $outstring='<font color="red">Unable to publish file, it contains duplicated ID(s), ID(s) need to be unique. The duplicated ID(s) are: '.join(', ',@duplicatedids).'</font>';
                    627: 	return ($outstring,1);
                    628:     }
1.86      albertel  629:     if ($needsfixup) {
                    630: 	print $logfile "Needs ID and/or index fixup\n".
                    631: 	    "Max ID   : $maxid (min 10)\n".
                    632:                 "Max Index: $maxindex (min 10)\n";
                    633:     }
                    634:     my $outstring='';
                    635:     my @parser;
                    636:     $parser[0]=HTML::LCParser->new(\$content);
                    637:     $parser[-1]->xml_mode(1);
                    638:     my $token;
                    639:     while (@parser) {
                    640: 	while ($token=$parser[-1]->get_token) {
                    641: 	    if ($token->[0] eq 'S') {
                    642: 		my $counter;
                    643: 		my $tag=$token->[1];
                    644: 		my $lctag=lc($tag);
                    645: 		if ($lctag eq 'allow') {
                    646: 		    $allow{$token->[2]->{'src'}}=1;
                    647: 		    next;
                    648: 		}
                    649: 		my %parms=%{$token->[2]};
                    650: 		$counter=$addid{$tag};
                    651: 		if (!$counter) { $counter=$addid{$lctag}; }
                    652: 		if ($counter) {
                    653: 		    if ($counter eq 'id') {
                    654: 			unless (defined($parms{'id'})) {
                    655: 			    $maxid++;
                    656: 			    $parms{'id'}=$maxid;
                    657: 			    print $logfile 'ID: '.$tag.':'.$maxid."\n";
                    658: 			}
                    659: 		    } elsif ($counter eq 'index') {
                    660: 			unless (defined($parms{'index'})) {
                    661: 			    $maxindex++;
                    662: 			    $parms{'index'}=$maxindex;
                    663: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
                    664: 			}
                    665: 		    }
                    666: 		}
                    667: 		foreach my $type ('src','href','background','bgimg') {
                    668: 		    foreach my $key (keys(%parms)) {
                    669: 			if ($key =~ /^$type$/i) {
                    670: 			    $parms{$key}=&set_allow(\%allow,$logfile,
                    671: 						    $target,$tag,
                    672: 						    $parms{$key});
                    673: 			}
                    674: 		    }
                    675: 		}
                    676: 		# probably a <randomlabel> image type <label>
1.135     albertel  677: 		# or a <image> tag inside <imageresponse>
                    678: 		if (($lctag eq 'label' && defined($parms{'description'}))
                    679: 		    ||
                    680: 		    ($lctag eq 'image')) {
1.86      albertel  681: 		    my $next_token=$parser[-1]->get_token();
                    682: 		    if ($next_token->[0] eq 'T') {
                    683: 			$next_token->[1]=&set_allow(\%allow,$logfile,
                    684: 						    $target,$tag,
                    685: 						    $next_token->[1]);
                    686: 		    }
                    687: 		    $parser[-1]->unget_token($next_token);
                    688: 		}
                    689: 		if ($lctag eq 'applet') {
                    690: 		    my $codebase='';
                    691: 		    if (defined($parms{'codebase'})) {
                    692: 			my $oldcodebase=$parms{'codebase'};
                    693: 			unless ($oldcodebase=~/\/$/) {
                    694: 			    $oldcodebase.='/';
                    695: 			}
                    696: 			$codebase=&urlfixup($oldcodebase,$target);
                    697: 			$codebase=~s/\/$//;    
                    698: 			if ($codebase ne $oldcodebase) {
                    699: 			    $parms{'codebase'}=$codebase;
                    700: 			    print $logfile 'URL codebase: '.$tag.':'.
                    701: 				$oldcodebase.' - '.
                    702: 				    $codebase."\n";
                    703: 			}
                    704: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
                    705: 		    } else {
                    706: 			foreach ('archive','code','object') {
                    707: 			    if (defined($parms{$_})) {
                    708: 				my $oldurl=$parms{$_};
                    709: 				my $newurl=&urlfixup($oldurl,$target);
                    710: 				$newurl=~s/\/[^\/]+$/\/\*/;
                    711: 				print $logfile 'Allow: applet '.$_.':'.
                    712: 				    $oldurl.' allows '.
                    713: 					$newurl."\n";
                    714: 				$allow{&absoluteurl($newurl,$target)}=1;
                    715: 			    }
                    716: 			}
                    717: 		    }
                    718: 		}
                    719: 		my $newparmstring='';
                    720: 		my $endtag='';
                    721: 		foreach (keys %parms) {
                    722: 		    if ($_ eq '/') {
                    723: 			$endtag=' /';
                    724: 		    } else { 
                    725: 			my $quote=($parms{$_}=~/\"/?"'":'"');
                    726: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
                    727: 		    }
                    728: 		}
                    729: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
                    730: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
1.130     albertel  731: 		if ($lctag eq 'm' || $lctag eq 'script' 
1.131     albertel  732:                     || $lctag eq 'display' || $lctag eq 'tex') {
1.130     albertel  733: 		    $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
1.87      albertel  734: 		}
1.86      albertel  735: 	    } elsif ($token->[0] eq 'E') {
                    736: 		if ($token->[2]) {
                    737: 		    unless ($token->[1] eq 'allow') {
                    738: 			$outstring.='</'.$token->[1].'>';
                    739: 		    }
                    740: 		}
                    741: 	    } else {
                    742: 		$outstring.=$token->[1];
                    743: 	    }
                    744: 	}
                    745: 	pop(@parser);
                    746:     }
                    747: 
                    748:     if ($needsfixup) {
                    749: 	print $logfile "End of ID and/or index fixup\n".
                    750: 	    "Max ID   : $maxid (min 10)\n".
                    751: 		"Max Index: $maxindex (min 10)\n";
                    752:     } else {
                    753: 	print $logfile "Does not need ID and/or index fixup\n";
                    754:     }
                    755: 
1.106     albertel  756:     return ($outstring,0,%allow);
1.86      albertel  757: }
                    758: 
1.89      matthew   759: #########################################
                    760: #########################################
                    761: 
                    762: =pod
                    763: 
1.94      harris41  764: =item B<store_metadata>
1.89      matthew   765: 
                    766: Store the metadata in the metadata table in the loncapa database.
                    767: Uses lonmysql to access the database.
                    768: 
                    769: Inputs: \%metadata
                    770: 
                    771: Returns: (error,status).  error is undef on success, status is undef on error.
                    772: 
                    773: =cut
                    774: 
                    775: #########################################
                    776: #########################################
                    777: sub store_metadata {
                    778:     my %metadata = %{shift()};
                    779:     my $error;
                    780:     # Determine if the table exists
                    781:     my $status = &Apache::lonmysql::check_table('metadata');
                    782:     if (! defined($status)) {
                    783:         $error='<font color="red">WARNING: Cannot connect to '.
                    784:             'database!</font>';
                    785:         &Apache::lonnet::logthis($error);
                    786:         return ($error,undef);
                    787:     }
                    788:     if ($status == 0) {
                    789:         # It would be nice to actually create the table....
                    790:         $error ='<font color="red">WARNING: The metadata table does not '.
                    791:             'exist in the LON-CAPA database.</font>';
                    792:         &Apache::lonnet::logthis($error);
                    793:         return ($error,undef);
                    794:     }
                    795:     # Remove old value from table
                    796:     $status = &Apache::lonmysql::remove_from_table
                    797:         ('metadata','url',$metadata{'url'});
                    798:     if (! defined($status)) {
                    799:         $error = '<font color="red">Error when removing old values from '.
                    800:             'metadata table in LON-CAPA database.</font>';
                    801:         &Apache::lonnet::logthis($error);
                    802:         return ($error,undef);
                    803:     }
                    804:     # Store data in table.
                    805:     $status = &Apache::lonmysql::store_row('metadata',\%metadata);
                    806:     if (! defined($status)) {
                    807:         $error='<font color="red">Error occured storing new values in '.
                    808:             'metadata table in LON-CAPA database</font>';
                    809:         &Apache::lonnet::logthis($error);
                    810:         return ($error,undef);
                    811:     }
                    812:     return (undef,$status);
                    813: }
                    814: 
1.90      matthew   815: #########################################
                    816: #########################################
                    817: 
                    818: =pod
                    819: 
1.94      harris41  820: =item B<publish>
                    821: 
                    822: This is the workhorse function of this module.  This subroutine generates
                    823: backup copies, performs any automatic processing (prior to publication,
                    824: especially for rat and ssi files),
1.90      matthew   825: 
1.113     albertel  826: Returns a 2 element array, the first is the string to be shown to the
                    827: user, the second is an error code, either 1 (an error occured) or 0
                    828: (no error occurred)
                    829: 
1.94      harris41  830: I<Additional documentation needed.>
1.90      matthew   831: 
                    832: =cut
                    833: 
                    834: #########################################
                    835: #########################################
1.2       www       836: sub publish {
1.50      www       837: 
1.97      www       838:     my ($source,$target,$style,$batch)=@_;
1.2       www       839:     my $logfile;
1.4       www       840:     my $scrout='';
1.23      www       841:     my $allmeta='';
                    842:     my $content='';
1.36      www       843:     my %allow=();
1.4       www       844: 
1.2       www       845:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1.114     albertel  846: 	return ('<font color="red">No write permission to user directory, FAIL</font>',1);
1.2       www       847:     }
                    848:     print $logfile 
1.125     www       849: "\n\n================= Publish ".localtime()." Phase One  ================\n".$ENV{'user.name'}.'@'.$ENV{'user.domain'}."\n";
1.2       www       850: 
1.119     www       851:     if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
1.3       www       852: # ------------------------------------------------------- This needs processing
1.4       www       853: 
                    854: # ----------------------------------------------------------------- Backup Copy
1.3       www       855: 	my $copyfile=$source.'.save';
1.13      www       856:         if (copy($source,$copyfile)) {
1.3       www       857: 	    print $logfile "Copied original file to ".$copyfile."\n";
                    858:         } else {
1.13      www       859: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
1.114     albertel  860: 	    return ("<font color=\"red\">Failed to write backup copy, $!,FAIL</font>",1);
1.3       www       861:         }
1.4       www       862: # ------------------------------------------------------------- IDs and indices
1.86      albertel  863: 	
1.106     albertel  864: 	my ($outstring,$error);
                    865: 	($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
                    866: 							$target);
1.113     albertel  867: 	if ($error) { return ($outstring,$error); }
1.36      www       868: # ------------------------------------------------------------ Construct Allows
1.62      www       869:     
1.44      www       870: 	$scrout.='<h3>Dependencies</h3>';
1.62      www       871:         my $allowstr='';
1.73      albertel  872:         foreach (sort(keys(%allow))) {
1.59      www       873: 	   my $thisdep=$_;
1.73      albertel  874: 	   if ($thisdep !~ /[^\s]/) { next; }
1.62      www       875:            unless ($style eq 'rat') { 
                    876:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
                    877: 	   }
1.120     albertel  878:            $scrout.='<br />';
1.59      www       879:            unless ($thisdep=~/\*/) {
                    880: 	       $scrout.='<a href="'.$thisdep.'">';
1.44      www       881:            }
1.59      www       882:            $scrout.='<tt>'.$thisdep.'</tt>';
                    883:            unless ($thisdep=~/\*/) {
1.44      www       884: 	       $scrout.='</a>';
1.59      www       885:                if (
                    886:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                    887:                                             $thisdep.'.meta') eq '-1') {
1.94      harris41  888: 		   $scrout.= ' - <font color="red">Currently not available'.
                    889: 		       '</font>';
1.59      www       890:                } else {
                    891:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
                    892:                              &Apache::lonnet::declutter($thisdep).'___usage'
                    893:                                  => time);
                    894:                    $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
                    895:                    if ((defined($1)) && (defined($2))) {
1.92      albertel  896:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
                    897: 					   $1,$2);
1.59      www       898: 		   }
                    899: 	       }
1.44      www       900:            }
1.65      harris41  901:         }
1.83      www       902:         $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
1.62      www       903: 
1.136     www       904: ### FIXME: is this really what we want?
1.137     albertel  905: # I dont' think so, to will corrupt any UTF-8 resources at least, 
                    906: # and any encoding other than ISO-8859-1 will probably break
1.76      albertel  907: 	#Encode any High ASCII characters
1.137     albertel  908: 	#$outstring=&HTML::Entities::encode($outstring,"\200-\377");
1.94      harris41  909: # ------------------------------------------------------------- Write modified.
1.37      www       910: 
1.4       www       911:         {
                    912:           my $org;
                    913:           unless ($org=Apache::File->new('>'.$source)) {
                    914:              print $logfile "No write permit to $source\n";
1.136     www       915:              return ('<font color="red">'.&mt('No write permission to').
                    916: 		     ' '.$source.
                    917: 		     ', '.&mt('FAIL').'</font>',1);
1.4       www       918: 	  }
1.94      harris41  919:           print($org $outstring);
1.4       www       920:         }
                    921: 	  $content=$outstring;
1.34      www       922: 
1.37      www       923:     }
1.94      harris41  924: # -------------------------------------------- Initial step done, now metadata.
1.7       www       925: 
1.94      harris41  926: # --------------------------------------- Storage for metadata keys and fields.
1.7       www       927: 
1.8       www       928:      %metadatafields=();
                    929:      %metadatakeys=();
                    930:      
                    931:      my %oldparmstores=();
1.44      www       932:      
1.97      www       933:     unless ($batch) {
1.136     www       934:      $scrout.='<h3>'.&mt('Metadata Information').' ' .
1.84      bowersj2  935:        Apache::loncommon::help_open_topic("Metadata_Description")
                    936:        . '</h3>';
1.97      www       937:     }
1.7       www       938: 
                    939: # ------------------------------------------------ First, check out environment
1.8       www       940:      unless (-e $source.'.meta') {
1.7       www       941:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
                    942: 	                          $ENV{'environment.middlename'}.' '.
                    943: 		                  $ENV{'environment.lastname'}.' '.
                    944: 		                  $ENV{'environment.generation'};
1.8       www       945:         $metadatafields{'author'}=~s/\s+/ /g;
                    946:         $metadatafields{'author'}=~s/\s+$//;
1.27      www       947:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
1.125     www       948: 	$metadatafields{'modifyinguser'}=$ENV{'user.name'}.'@'.
                    949: 	                                 $ENV{'user.domain'};
                    950: 	$metadatafields{'authorspace'}=$cuname.'@'.$cudom;
1.7       www       951: 
                    952: # ------------------------------------------------ Check out directory hierachy
                    953: 
                    954:         my $thisdisfn=$source;
1.122     albertel  955:         $thisdisfn=~s/^\/home\/\Q$cuname\E\///;
1.7       www       956: 
                    957:         my @urlparts=split(/\//,$thisdisfn);
                    958:         $#urlparts--;
                    959: 
1.27      www       960:         my $currentpath='/home/'.$cuname.'/';
1.7       www       961: 
1.140   ! albertel  962: 	my $prefix='../'x($#urlparts);
1.65      harris41  963:         foreach (@urlparts) {
1.7       www       964: 	    $currentpath.=$_.'/';
1.140   ! albertel  965:             $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
        !           966: 	    $prefix=~s|^\.\./||;
1.65      harris41  967:         }
1.7       www       968: 
                    969: # ------------------- Clear out parameters and stores (there should not be any)
                    970: 
1.65      harris41  971:         foreach (keys %metadatafields) {
1.7       www       972: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                    973: 		delete $metadatafields{$_};
                    974:             }
1.65      harris41  975:         }
1.7       www       976: 
1.8       www       977:     } else {
1.7       www       978: # ---------------------- Read previous metafile, remember parameters and stores
                    979: 
                    980:         $scrout.=&metaread($logfile,$source.'.meta');
                    981: 
1.65      harris41  982:         foreach (keys %metadatafields) {
1.7       www       983: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                    984:                 $oldparmstores{$_}=1;
                    985: 		delete $metadatafields{$_};
                    986:             }
1.65      harris41  987:         }
1.7       www       988:         
1.8       www       989:     }
1.7       www       990: 
1.4       www       991: # -------------------------------------------------- Parse content for metadata
1.119     www       992:     if (($style eq 'ssi') || ($style eq 'prv')) {
1.133     albertel  993: 	my $dir=$source;
                    994: 	$dir=~s-/[^/]*$--;
                    995: 	my $file=$source;
                    996: 	$file=(split('/',$file))[-1];
                    997:         $source=&Apache::lonnet::hreflocation($dir,$file);
                    998: 	$allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
1.32      www       999: 
1.19      albertel 1000:         &metaeval($allmeta);
1.37      www      1001:     }
1.7       www      1002: # ---------------- Find and document discrepancies in the parameters and stores
                   1003: 
1.116     albertel 1004:     my $chparms='';
                   1005:     foreach (sort keys %metadatafields) {
                   1006: 	if (($_=~/^parameter/) || ($_=~/^stores/)) {
                   1007: 	    unless ($_=~/\.\w+$/) { 
                   1008: 		unless ($oldparmstores{$_}) {
                   1009: 		    print $logfile 'New: '.$_."\n";
                   1010: 		    $chparms.=$_.' ';
                   1011: 		}
                   1012: 	    }
                   1013: 	}
                   1014:     }
                   1015:     if ($chparms) {
1.136     www      1016: 	$scrout.='<p><b>'.&mt('New parameters or stored values').
                   1017: 	    ':</b> '.$chparms.'</p>';
1.116     albertel 1018:     }
1.7       www      1019: 
1.116     albertel 1020:     $chparms='';
                   1021:     foreach (sort keys %oldparmstores) {
                   1022: 	if (($_=~/^parameter/) || ($_=~/^stores/)) {
                   1023: 	    unless (($metadatafields{$_.'.name'}) ||
                   1024: 		    ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
                   1025: 		print $logfile 'Obsolete: '.$_."\n";
                   1026: 		$chparms.=$_.' ';
                   1027: 	    }
                   1028: 	}
                   1029:     }
                   1030:     if ($chparms) {
1.136     www      1031: 	$scrout.='<p><b>'.&mt('Obsolete parameters or stored values').':</b> '.
1.120     albertel 1032: 	    $chparms.'</p>';
1.116     albertel 1033:     }
1.37      www      1034: 
1.8       www      1035: # ------------------------------------------------------- Now have all metadata
1.5       www      1036: 
1.116     albertel 1037:     my %keywords=();
1.97      www      1038:         
1.116     albertel 1039:     if (length($content)<500000) {
                   1040: 	my $textonly=$content;
                   1041: 	$textonly=~s/\<script[^\<]+\<\/script\>//g;
                   1042: 	$textonly=~s/\<m\>[^\<]+\<\/m\>//g;
                   1043: 	$textonly=~s/\<[^\>]*\>//g;
                   1044: 	$textonly=~tr/A-Z/a-z/;
                   1045: 	$textonly=~s/[\$\&][a-z]\w*//g;
                   1046: 	$textonly=~s/[^a-z\s]//g;
                   1047: 	
                   1048: 	foreach ($textonly=~m/(\w+)/g) {
                   1049: 	    unless ($nokey{$_}) {
                   1050: 		$keywords{$_}=1;
                   1051: 	    } 
                   1052: 	}
                   1053:     }
1.97      www      1054: 
                   1055:             
1.116     albertel 1056:     foreach (split(/\W+/,$metadatafields{'keywords'})) {
                   1057: 	$keywords{$_}=1;
                   1058:     }
1.97      www      1059: # --------------------------------------------------- Now we also have keywords
                   1060: # =============================================================================
                   1061: # INTERACTIVE MODE
                   1062: #
1.116     albertel 1063:     unless ($batch) {
1.8       www      1064:         $scrout.=
1.116     albertel 1065: 	    '<form name="pubform" action="/adm/publish" method="post">'.
                   1066:             '<p><input type="submit" value="Finalize Publication" /></p>'.
                   1067:             &hiddenfield('phase','two').
                   1068:             &hiddenfield('filename',$ENV{'form.filename'}).
                   1069: 	    &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
                   1070:             &hiddenfield('dependencies',join(',',keys %allow)).
                   1071:             &textfield('Title','title',$metadatafields{'title'}).
                   1072:             &textfield('Author(s)','author',$metadatafields{'author'}).
                   1073: 	    &textfield('Subject','subject',$metadatafields{'subject'});
1.5       www      1074: 
                   1075: # --------------------------------------------------- Scan content for keywords
1.7       www      1076: 
1.84      bowersj2 1077:         my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
1.77      matthew  1078: 	my $keywordout=<<"END";
                   1079: <script>
1.116     albertel 1080: function checkAll(field) {
1.77      matthew  1081:     for (i = 0; i < field.length; i++)
                   1082:         field[i].checked = true ;
                   1083: }
                   1084: 
1.116     albertel 1085: function uncheckAll(field) {
1.77      matthew  1086:     for (i = 0; i < field.length; i++)
                   1087:         field[i].checked = false ;
                   1088: }
                   1089: </script>
1.123     albertel 1090: <p><font color="#800000" face="helvetica"><b>KEYWORDS:</b></font>
                   1091:  $keywords_help</b>
1.120     albertel 1092: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)" /> 
                   1093: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)" /> 
                   1094: </p>
1.77      matthew  1095: <br />
1.117     albertel 1096: END
1.120     albertel 1097: 	$keywordout.='<table border="2"><tr>';
1.116     albertel 1098: 	my $colcount=0;
                   1099: 
                   1100: 	foreach (sort keys %keywords) {
1.120     albertel 1101: 	    $keywordout.='<td><input type="checkbox" name="keywords" value="'.$_.'"';
1.116     albertel 1102: 	    if ($metadatafields{'keywords'}) {
1.122     albertel 1103: 		if ($metadatafields{'keywords'}=~/\Q$_\E/) {
1.120     albertel 1104: 		    $keywordout.=' checked="on"';
1.116     albertel 1105: 		}
                   1106: 	    } elsif (&Apache::loncommon::keyword($_)) {
1.120     albertel 1107: 		$keywordout.=' checked="on"';
1.116     albertel 1108: 	    }
1.120     albertel 1109: 	    $keywordout.=' />'.$_.'</td>';
1.116     albertel 1110: 	    if ($colcount>10) {
                   1111: 		$keywordout.="</tr><tr>\n";
                   1112: 		$colcount=0;
                   1113: 	    }
                   1114: 	    $colcount++;
                   1115: 	}
                   1116: 
1.51      www      1117: 	$keywordout.='</tr></table>';
                   1118: 
1.116     albertel 1119: 	$scrout.=$keywordout;
1.9       www      1120: 
1.116     albertel 1121: 	$scrout.=&textfield('Additional Keywords','addkey','');
1.12      www      1122: 
1.116     albertel 1123: 	$scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
1.9       www      1124: 
1.116     albertel 1125: 	$scrout.=
1.123     albertel 1126: 	    "\n<p><font color=\"#800000\" face=\"helvetica\"><b>ABSTRACT:".
                   1127: 	    "</b></font></p><br />".
                   1128: 	    '<textarea cols="80" rows="5" name="abstract">'.
1.120     albertel 1129: 	    $metadatafields{'abstract'}.'</textarea></p>';
1.9       www      1130: 
1.11      www      1131: 	$source=~/\.(\w+)$/;
                   1132: 
                   1133: 	$scrout.=&hiddenfield('mime',$1);
                   1134: 
1.123     albertel 1135: 	my $defaultlanguage=$metadatafields{'language'};
                   1136: 	$defaultlanguage =~ s/\s*notset\s*//g;
                   1137: 	$defaultlanguage =~ s/^,\s*//g;
                   1138: 	$defaultlanguage =~ s/,\s*$//g;
                   1139: 
1.116     albertel 1140: 	$scrout.=&selectbox('Language','language',
1.123     albertel 1141: 			    $defaultlanguage,
1.70      harris41 1142: 			    \&Apache::loncommon::languagedescription,
1.65      harris41 1143: 			    (&Apache::loncommon::languageids),
1.116     albertel 1144: 			   );
1.11      www      1145: 
1.116     albertel 1146: 	unless ($metadatafields{'creationdate'}) {
1.11      www      1147: 	    $metadatafields{'creationdate'}=time;
1.116     albertel 1148: 	}
                   1149: 	$scrout.=&hiddenfield('creationdate',
                   1150: 			      &Apache::loncommon::unsqltime($metadatafields{'creationdate'}));
                   1151: 
                   1152: 	$scrout.=&hiddenfield('lastrevisiondate',time);
1.11      www      1153: 
                   1154: 
1.10      www      1155: 	$scrout.=&textfield('Publisher/Owner','owner',
1.116     albertel 1156: 			    $metadatafields{'owner'});
1.84      bowersj2 1157: 
1.94      harris41 1158: # -------------------------------------------------- Correct copyright for rat.
1.121     www      1159:         my $defaultoption=$metadatafields{'copyright'};
                   1160:         unless ($defaultoption) { $defaultoption='default'; }
1.116     albertel 1161: 	unless ($style eq 'prv') {
                   1162: 	    if ($style eq 'rat') {
                   1163: 		if ($metadatafields{'copyright'} eq 'public') { 
                   1164: 		    delete $metadatafields{'copyright'};
1.121     www      1165:                     $defaultoption='default';
1.116     albertel 1166: 		}
                   1167: 		$scrout.=&selectbox('Copyright/Distribution','copyright',
1.121     www      1168: 				    $defaultoption,
1.116     albertel 1169: 				    \&Apache::loncommon::copyrightdescription,
                   1170: 				    (grep !/^public$/,(&Apache::loncommon::copyrightids)));
                   1171: 	    } else {
                   1172: 		$scrout.=&selectbox('Copyright/Distribution','copyright',
1.121     www      1173: 				    $defaultoption,
1.116     albertel 1174: 				    \&Apache::loncommon::copyrightdescription,
                   1175: 				    (&Apache::loncommon::copyrightids));
                   1176: 	    }
                   1177:     
                   1178: 	    my $copyright_help =
                   1179: 		Apache::loncommon::help_open_topic('Publishing_Copyright');
                   1180: 	    $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
                   1181: 	    $scrout.=&textfield('Custom Distribution File','customdistributionfile',
                   1182: 				$metadatafields{'customdistributionfile'}).
                   1183: 				    $copyright_help;
1.136     www      1184: 	    my $uctitle=uc(&mt('Obsolete'));
                   1185:             $scrout.=
                   1186: 		"\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
                   1187: 		'</b></font> <input type="checkbox" name="obsolete" ';
                   1188: 	    if ($metadatafields{'obsolete'}) {
                   1189: 		$scrout.=' checked="1" ';
                   1190: 	    }
                   1191: 	    $scrout.='/ ></p>'.
                   1192: 		&textfield('Suggested Replacement for Obsolete File',
                   1193: 				    'obsoletereplacement',
                   1194: 				    $metadatafields{'obsoletereplacement'});
1.116     albertel 1195: 	} else {
                   1196: 	    $scrout.=&hiddenfield('copyright','private');
1.65      harris41 1197: 	}
1.136     www      1198: 	return ($scrout.'<p><input type="submit" value="'.
                   1199: 		&mt('Finalize Publication').'" /></p></form>',0);
1.97      www      1200: # =============================================================================
                   1201: # BATCH MODE
                   1202: #
1.116     albertel 1203:     } else {
1.97      www      1204: # Transfer metadata directly to environment for stage 2
1.116     albertel 1205: 	foreach (keys %metadatafields) {
                   1206: 	    $ENV{'form.'.$_}=$metadatafields{$_};
                   1207: 	}
                   1208: 	$ENV{'form.addkey'}='';
                   1209: 	$ENV{'form.keywords'}='';
                   1210: 	foreach (keys %keywords) {
                   1211: 	    if ($metadatafields{'keywords'}) {
1.122     albertel 1212: 		if ($metadatafields{'keywords'}=~/\Q$_\E/) { 
1.116     albertel 1213: 		    $ENV{'form.keywords'}.=$_.','; 
                   1214: 		}
                   1215: 	    } elsif (&Apache::loncommon::keyword($_)) {
                   1216: 		$ENV{'form.keywords'}.=$_.',';
                   1217: 	    }
                   1218: 	}
                   1219: 	$ENV{'form.keywords'}=~s/\,$//;
                   1220: 	unless ($ENV{'form.creationdate'}) { $ENV{'form.creationdate'}=time; }
                   1221: 	$ENV{'form.lastrevisiondate'}=time;
                   1222: 	if ((($style eq 'rat') && ($ENV{'form.copyright'} eq 'public')) ||
                   1223: 	    (!$ENV{'form.copyright'})) { 
                   1224: 	    $ENV{'form.copyright'}='default';
                   1225: 	}
                   1226: 	$ENV{'form.allmeta'}=&Apache::lonnet::escape($allmeta);
                   1227: 	return ($scrout,0);
1.97      www      1228:     }
1.2       www      1229: }
1.1       www      1230: 
1.90      matthew  1231: #########################################
                   1232: #########################################
                   1233: 
                   1234: =pod 
                   1235: 
1.94      harris41 1236: =item B<phasetwo>
1.90      matthew  1237: 
                   1238: Render second interface showing status of publication steps.
                   1239: This is publication step two.
                   1240: 
1.94      harris41 1241: Parameters:
                   1242: 
                   1243: =over 4
                   1244: 
                   1245: =item I<$source>
                   1246: 
                   1247: =item I<$target>
                   1248: 
                   1249: =item I<$style>
                   1250: 
                   1251: =item I<$distarget>
                   1252: 
                   1253: =back
                   1254: 
                   1255: Returns:
                   1256: 
                   1257: =over 4
                   1258: 
                   1259: =item Scalar string
                   1260: 
                   1261: String contains status (errors and warnings) and information associated with
1.100     matthew  1262: the server's attempts at publication.     
1.94      harris41 1263: 
1.90      matthew  1264: =cut
1.12      www      1265: 
1.100     matthew  1266: #'stupid emacs
1.90      matthew  1267: #########################################
                   1268: #########################################
1.11      www      1269: sub phasetwo {
                   1270: 
1.100     matthew  1271:     my ($r,$source,$target,$style,$distarget,$batch)=@_;
1.102     www      1272:     $source=~s/\/+/\//g;
                   1273:     $target=~s/\/+/\//g;
1.109     www      1274: 
                   1275:     if ($target=~/\_\_\_/) {
1.110     www      1276: 	$r->print(
1.136     www      1277:  '<font color="red">'.&mt('Unsupported character combination').
                   1278: 		  ' "<tt>___</tt>" '.&mt('in filename, FAIL').'</font>');
1.110     www      1279:         return 0;
1.109     www      1280:     }
1.102     www      1281:     $distarget=~s/\/+/\//g;
1.11      www      1282:     my $logfile;
                   1283:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1.110     www      1284: 	$r->print(
1.136     www      1285:         '<font color="red">'.
                   1286: 		&mt('No write permission to user directory, FAIL').'</font>');
1.110     www      1287:         return 0;
1.11      www      1288:     }
                   1289:     print $logfile 
1.125     www      1290:         "\n================= Publish ".localtime()." Phase Two  ================\n".$ENV{'user.name'}.'@'.$ENV{'user.domain'}."\n";
1.100     matthew  1291:     
                   1292:     %metadatafields=();
                   1293:     %metadatakeys=();
                   1294:     
                   1295:     &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
                   1296:     
                   1297:     $metadatafields{'title'}=$ENV{'form.title'};
                   1298:     $metadatafields{'author'}=$ENV{'form.author'};
                   1299:     $metadatafields{'subject'}=$ENV{'form.subject'};
                   1300:     $metadatafields{'notes'}=$ENV{'form.notes'};
                   1301:     $metadatafields{'abstract'}=$ENV{'form.abstract'};
                   1302:     $metadatafields{'mime'}=$ENV{'form.mime'};
                   1303:     $metadatafields{'language'}=$ENV{'form.language'};
1.103     www      1304:     $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
                   1305:     $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
1.100     matthew  1306:     $metadatafields{'owner'}=$ENV{'form.owner'};
                   1307:     $metadatafields{'copyright'}=$ENV{'form.copyright'};
1.115     www      1308:     $metadatafields{'customdistributionfile'}=
                   1309:                                  $ENV{'form.customdistributionfile'};
1.138     www      1310:     $metadatafields{'obsolete'}=$ENV{'form.obsolete'};
                   1311:     $metadatafields{'obsoletereplacement'}=
                   1312: 	                        $ENV{'form.obsoletereplacement'};
1.100     matthew  1313:     $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
                   1314:     
                   1315:     my $allkeywords=$ENV{'form.addkey'};
                   1316:     if (exists($ENV{'form.keywords'})) {
                   1317:         if (ref($ENV{'form.keywords'})) {
                   1318:             $allkeywords .= ','.join(',',@{$ENV{'form.keywords'}});
                   1319:         } else {
                   1320:             $allkeywords .= ','.$ENV{'form.keywords'};
                   1321:         }
                   1322:     }
                   1323:     $allkeywords=~s/\W+/\,/;
                   1324:     $allkeywords=~s/^\,//;
                   1325:     $metadatafields{'keywords'}=$allkeywords;
                   1326:     
                   1327:     {
                   1328:         print $logfile "\nWrite metadata file for ".$source;
                   1329:         my $mfh;
                   1330:         unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
                   1331:             return 
1.136     www      1332:                 '<font color="red">'.&mt('Could not write metadata, FAIL').
                   1333: 		'</font>';
1.100     matthew  1334:         }
                   1335:         foreach (sort keys %metadatafields) {
                   1336:             unless ($_=~/\./) {
                   1337:                 my $unikey=$_;
                   1338:                 $unikey=~/^([A-Za-z]+)/;
                   1339:                 my $tag=$1;
                   1340:                 $tag=~tr/A-Z/a-z/;
                   1341:                 print $mfh "\n\<$tag";
                   1342:                 foreach (split(/\,/,$metadatakeys{$unikey})) {
                   1343:                     my $value=$metadatafields{$unikey.'.'.$_};
                   1344:                     $value=~s/\"/\'\'/g;
                   1345:                     print $mfh ' '.$_.'="'.$value.'"';
                   1346:                 }
                   1347:                 print $mfh '>'.
                   1348:                     &HTML::Entities::encode($metadatafields{$unikey})
                   1349:                         .'</'.$tag.'>';
                   1350:             }
                   1351:         }
1.136     www      1352:         $r->print('<p>'.&mt('Wrote Metadata').'</p>');
1.100     matthew  1353:         print $logfile "\nWrote metadata";
                   1354:     }
                   1355:     
                   1356: # -------------------------------- Synchronize entry with SQL metadata database
1.12      www      1357: 
1.89      matthew  1358:     $metadatafields{'url'} = $distarget;
                   1359:     $metadatafields{'version'} = 'current';
                   1360:     unless ($metadatafields{'copyright'} eq 'priv') {
                   1361:         my ($error,$success) = &store_metadata(\%metadatafields);
1.91      matthew  1362:         if ($success) {
1.138     www      1363:             $r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
1.89      matthew  1364:             print $logfile "\nSynchronized SQL metadata database";
                   1365:         } else {
1.100     matthew  1366:             $r->print($error);
1.89      matthew  1367:             print $logfile "\n".$error;
                   1368:         }
                   1369:     } else {
1.136     www      1370:         $r->print('<p>'.
                   1371: 	     &mt('Private Publication - did not synchronize database').'</p>');
1.89      matthew  1372:         print $logfile "\nPrivate: Did not synchronize data into ".
                   1373:             "SQL metadata database";
1.24      harris41 1374:     }
1.12      www      1375: # ----------------------------------------------------------- Copy old versions
                   1376:    
1.100     matthew  1377:     if (-e $target) {
                   1378:         my $filename;
                   1379:         my $maxversion=0;
                   1380:         $target=~/(.*)\/([^\/]+)\.(\w+)$/;
                   1381:         my $srcf=$2;
                   1382:         my $srct=$3;
                   1383:         my $srcd=$1;
                   1384:         unless ($srcd=~/^\/home\/httpd\/html\/res/) {
                   1385:             print $logfile "\nPANIC: Target dir is ".$srcd;
1.114     albertel 1386:             return "<font color=\"red\">Invalid target directory, FAIL</font>";
1.100     matthew  1387:         }
                   1388:         opendir(DIR,$srcd);
                   1389:         while ($filename=readdir(DIR)) {
                   1390:             if (-l $srcd.'/'.$filename) {
                   1391:                 unlink($srcd.'/'.$filename);
                   1392:                 unlink($srcd.'/'.$filename.'.meta');
                   1393:             } else {
1.118     albertel 1394:                 if ($filename=~/\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
1.100     matthew  1395:                     $maxversion=($1>$maxversion)?$1:$maxversion;
                   1396:                 }
                   1397:             }
                   1398:         }
                   1399:         closedir(DIR);
                   1400:         $maxversion++;
1.120     albertel 1401:         $r->print('<p>Creating old version '.$maxversion.'</p>');
1.125     www      1402:         print $logfile "\nCreating old version ".$maxversion."\n";
1.100     matthew  1403:         
                   1404:         my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
                   1405:         
1.13      www      1406:         if (copy($target,$copyfile)) {
1.12      www      1407: 	    print $logfile "Copied old target to ".$copyfile."\n";
1.136     www      1408:             $r->print('<p>'.&mt('Copied old target file').'</p>');
1.12      www      1409:         } else {
1.13      www      1410: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
1.136     www      1411:             return "<font color=\"red\">".&mt('Failed to copy old target').
                   1412: 		", $!, ".&mt('FAIL')."</font>";
1.12      www      1413:         }
1.100     matthew  1414:         
1.12      www      1415: # --------------------------------------------------------------- Copy Metadata
                   1416: 
                   1417: 	$copyfile=$copyfile.'.meta';
1.100     matthew  1418:         
1.13      www      1419:         if (copy($target.'.meta',$copyfile)) {
1.14      www      1420: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
1.136     www      1421:             $r->print('<p>'.&mt('Copied old metadata').'</p>')
1.12      www      1422:         } else {
1.13      www      1423: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1.14      www      1424:             if (-e $target.'.meta') {
1.100     matthew  1425:                 return 
1.136     www      1426:                     "<font color=\"red\">".
                   1427: &mt('Failed to write old metadata copy').", $!, ".&mt('FAIL')."</font>";
1.14      www      1428: 	    }
1.12      www      1429:         }
1.100     matthew  1430:         
                   1431:         
                   1432:     } else {
1.138     www      1433:         $r->print('<p>'.&mt('Initial version').'</p>');
1.100     matthew  1434:         print $logfile "\nInitial version";
                   1435:     }
1.12      www      1436: 
                   1437: # ---------------------------------------------------------------- Write Source
1.100     matthew  1438:     my $copyfile=$target;
                   1439:     
                   1440:     my @parts=split(/\//,$copyfile);
                   1441:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1442:     
                   1443:     my $count;
                   1444:     for ($count=5;$count<$#parts;$count++) {
                   1445:         $path.="/$parts[$count]";
                   1446:         if ((-e $path)!=1) {
                   1447:             print $logfile "\nCreating directory ".$path;
1.136     www      1448:             $r->print('<p>'.&mt('Created directory').' '.$parts[$count].'</p>');
1.100     matthew  1449:             mkdir($path,0777);
1.12      www      1450:         }
1.100     matthew  1451:     }
                   1452:     
                   1453:     if (copy($source,$copyfile)) {
                   1454:         print $logfile "\nCopied original source to ".$copyfile."\n";
1.136     www      1455:         $r->print('<p>'.&mt('Copied source file').'</p>');
1.100     matthew  1456:     } else {
                   1457:         print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
1.136     www      1458:         return "<font color=\"red\">".
                   1459: 	    &mt('Failed to copy source').", $!, ".&mt('FAIL')."</font>";
1.100     matthew  1460:     }
                   1461:     
1.12      www      1462: # --------------------------------------------------------------- Copy Metadata
                   1463: 
1.100     matthew  1464:     $copyfile=$copyfile.'.meta';
                   1465:     
                   1466:     if (copy($source.'.meta',$copyfile)) {
                   1467:         print $logfile "\nCopied original metadata to ".$copyfile."\n";
1.136     www      1468:         $r->print('<p>'.&mt('Copied metadata').'</p>');
1.100     matthew  1469:     } else {
                   1470:         print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
                   1471:         return 
1.136     www      1472:             "<font color=\"red\">".&mt('Failed to write metadata copy').", $!, ".&mt('FAIL')."</font>";
1.100     matthew  1473:     }
                   1474:     $r->rflush;
1.12      www      1475: # --------------------------------------------------- Send update notifications
                   1476: 
1.85      albertel 1477:     my @subscribed=&get_subscribed_hosts($target);
                   1478:     foreach my $subhost (@subscribed) {
1.136     www      1479: 	$r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
1.85      albertel 1480: 	print $logfile "\nNotifying host ".$subhost.':';
                   1481: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
1.120     albertel 1482: 	$r->print($reply.'</p><br />');$r->rflush;
1.85      albertel 1483: 	print $logfile $reply;
1.20      www      1484:     }
1.100     matthew  1485:     
1.20      www      1486: # ---------------------------------------- Send update notifications, meta only
                   1487: 
1.85      albertel 1488:     my @subscribedmeta=&get_subscribed_hosts("$target.meta");
                   1489:     foreach my $subhost (@subscribedmeta) {
1.136     www      1490: 	$r->print('<p>'.
                   1491: &mt('Notifying host for metadata only').' '.$subhost.':');$r->rflush;
1.85      albertel 1492: 	print $logfile "\nNotifying host for metadata only ".$subhost.':';
                   1493: 	my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
                   1494: 					    $subhost);
1.120     albertel 1495: 	$r->print($reply.'</p><br />');$r->rflush;
1.85      albertel 1496: 	print $logfile $reply;
1.12      www      1497:     }
1.100     matthew  1498:     
1.101     www      1499: # --------------------------------------------------- Notify subscribed courses
                   1500:     my %courses=&coursedependencies($target);
                   1501:     my $now=time;
                   1502:     foreach (keys %courses) {
1.136     www      1503: 	$r->print('<p>'.&mt('Notifying course').' '.$_.':');$r->rflush;
1.101     www      1504: 	print $logfile "\nNotifying host ".$_.':';
                   1505:         my ($cdom,$cname)=split(/\_/,$_);
                   1506: 	my $reply=&Apache::lonnet::cput
                   1507:                   ('versionupdate',{$target => $now},$cdom,$cname);
1.120     albertel 1508: 	$r->print($reply.'</p><br />');$r->rflush;
1.101     www      1509: 	print $logfile $reply;
                   1510:     }
1.12      www      1511: # ------------------------------------------------ Provide link to new resource
1.100     matthew  1512:     unless ($batch) {
                   1513:         my $thisdistarget=$target;
1.122     albertel 1514:         $thisdistarget=~s/^\Q$docroot\E//;
1.100     matthew  1515:         
                   1516:         my $thissrc=$source;
                   1517:         $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
                   1518:         
                   1519:         my $thissrcdir=$thissrc;
                   1520:         $thissrcdir=~s/\/[^\/]+$/\//;
                   1521:         
                   1522:         
                   1523:         $r->print(
1.120     albertel 1524:            '<hr /><a href="'.$thisdistarget.'"><font size="+2">'.
1.138     www      1525:            &mt('View Published Version').'</font></a>'.
                   1526:            '<p><a href="'.$thissrc.'"><font size=+2>'.
                   1527: 		  &mt('Back to Source').'</font></a></p>'.
1.100     matthew  1528:            '<p><a href="'.$thissrcdir.
1.138     www      1529:                    '"><font size="+2">'.
                   1530: 		  &mt('Back to Source Directory').'</font></a></p>');
1.100     matthew  1531:     }
1.11      www      1532: }
                   1533: 
1.95      www      1534: #########################################
                   1535: 
                   1536: sub batchpublish {
1.97      www      1537:     my ($r,$srcfile,$targetfile)=@_;
1.132     albertel 1538:     #publication pollutes %ENV with form.* values
                   1539:     my %oldENV=%ENV;
1.102     www      1540:     $srcfile=~s/\/+/\//g;
                   1541:     $targetfile=~s/\/+/\//g;
1.95      www      1542:     my $thisdisfn=$srcfile;
                   1543:     $thisdisfn=~s/\/home\/korte\/public_html\///;
                   1544:     $srcfile=~s/\/+/\//g;
1.96      www      1545: 
1.97      www      1546:     my $docroot=$r->dir_config('lonDocRoot');
                   1547:     my $thisdistarget=$targetfile;
1.122     albertel 1548:     $thisdistarget=~s/^\Q$docroot\E//;
1.97      www      1549: 
1.96      www      1550: 
1.139     albertel 1551:     %metadatafields=();
                   1552:     %metadatakeys=();
                   1553:     $srcfile=~/\.(\w+)$/;
                   1554:     my $thistype=$1;
1.97      www      1555: 
                   1556: 
1.139     albertel 1557:     my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1.96      www      1558:      
1.138     www      1559:     $r->print('<h2>'.&mt('Publishing').' <tt>'.$thisdisfn.'</tt></h2>');
1.97      www      1560: 
                   1561: # phase one takes
                   1562: #  my ($source,$target,$style,$batch)=@_;
1.113     albertel 1563:     my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
                   1564:     $r->print('<p>'.$outstring.'</p>');
1.96      www      1565: # phase two takes
                   1566: # my ($source,$target,$style,$distarget,batch)=@_;
1.97      www      1567: # $ENV{'form.allmeta'},$ENV{'form.title'},$ENV{'form.author'},...
1.113     albertel 1568:     if (!$error) {
                   1569: 	$r->print('<p>');
                   1570: 	&phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
                   1571: 	$r->print('</p>');
                   1572:     }
1.132     albertel 1573:     %ENV=%oldENV;
1.97      www      1574:     return '';
1.95      www      1575: }
1.1       www      1576: 
1.90      matthew  1577: #########################################
1.95      www      1578: 
                   1579: sub publishdirectory {
                   1580:     my ($r,$fn,$thisdisfn)=@_;
1.102     www      1581:     $fn=~s/\/+/\//g;
                   1582:     $thisdisfn=~s/\/+/\//g;
1.96      www      1583:     my $resdir=
1.139     albertel 1584: 	$Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cudom.'/'.$cuname.'/'.
                   1585: 	$thisdisfn;
                   1586:     $r->print('<h1>Directory <tt>'.$thisdisfn.'</tt></h1>'.
                   1587: 	      'Target: <tt>'.$resdir.'</tt><br />');
                   1588: 
                   1589:     my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
                   1590: 
                   1591:     opendir(DIR,$fn);
                   1592:     my @files=sort(readdir(DIR));
                   1593:     foreach my $filename (@files) {
                   1594: 	my ($cdev,$cino,$cmode,$cnlink,
1.95      www      1595:             $cuid,$cgid,$crdev,$csize,
                   1596:             $catime,$cmtime,$cctime,
                   1597:             $cblksize,$cblocks)=stat($fn.'/'.$filename);
                   1598: 
1.139     albertel 1599: 	my $extension='';
                   1600: 	if ($filename=~/\.(\w+)$/) { $extension=$1; }
                   1601: 	if ($cmode&$dirptr) {
                   1602: 	    if (($filename!~/^\./) && ($ENV{'form.pubrec'})) {
                   1603: 		&publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
                   1604: 	    }
                   1605: 	} elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
                   1606: 		 ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
1.96      www      1607: # find out publication status and/or exiting metadata
1.139     albertel 1608: 	    my $publishthis=0;
                   1609: 	    if (-e $resdir.'/'.$filename) {
1.96      www      1610: 	        my ($rdev,$rino,$rmode,$rnlink,
1.139     albertel 1611: 		    $ruid,$rgid,$rrdev,$rsize,
                   1612: 		    $ratime,$rmtime,$rctime,
                   1613: 		    $rblksize,$rblocks)=stat($resdir.'/'.$filename);
1.124     www      1614: 	        if (($rmtime<$cmtime) || ($ENV{'form.forcerepub'})) {
1.96      www      1615: # previously published, modified now
                   1616: 		    $publishthis=1;
                   1617:                 }
1.139     albertel 1618: 	    } else {
1.96      www      1619: # never published
1.139     albertel 1620: 		$publishthis=1;
                   1621: 	    }
                   1622: 	    if ($publishthis) {
1.97      www      1623:                 &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
1.139     albertel 1624: 	    } else {
                   1625: 		$r->print('<br />Skipping '.$filename.'<br />');
                   1626: 	    }
                   1627: 	    $r->rflush();
                   1628: 	}
                   1629:     }
                   1630:     closedir(DIR);
1.95      www      1631: }
1.90      matthew  1632: #########################################
                   1633: 
                   1634: =pod
                   1635: 
1.94      harris41 1636: =item B<handler>
1.90      matthew  1637: 
                   1638: A basic outline of the handler subroutine follows.
                   1639: 
                   1640: =over 4
                   1641: 
1.94      harris41 1642: =item *
                   1643: 
                   1644: Get query string for limited number of parameters.
                   1645: 
                   1646: =item *
                   1647: 
                   1648: Check filename.
                   1649: 
                   1650: =item *
                   1651: 
                   1652: File is there and owned, init lookup tables.
                   1653: 
                   1654: =item *
1.90      matthew  1655: 
1.94      harris41 1656: Start page output.
1.90      matthew  1657: 
1.94      harris41 1658: =item *
1.90      matthew  1659: 
1.94      harris41 1660: Evaluate individual file, and then output information.
1.90      matthew  1661: 
1.94      harris41 1662: =item *
1.90      matthew  1663: 
1.94      harris41 1664: Publishing from $thisfn to $thistarget with $thisembstyle.
1.90      matthew  1665: 
                   1666: =back
                   1667: 
                   1668: =cut
                   1669: 
                   1670: #########################################
                   1671: #########################################
1.1       www      1672: sub handler {
1.139     albertel 1673:     my $r=shift;
1.2       www      1674: 
1.139     albertel 1675:     if ($r->header_only) {
                   1676: 	&Apache::loncommon::content_type($r,'text/html');
                   1677: 	$r->send_http_header;
                   1678: 	return OK;
                   1679:     }
1.2       www      1680: 
1.43      www      1681: # Get query string for limited number of parameters
                   1682: 
1.80      matthew  1683:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1684:                                             ['filename']);
1.43      www      1685: 
1.2       www      1686: # -------------------------------------------------------------- Check filename
                   1687: 
1.139     albertel 1688:     my $fn=&Apache::lonnet::unescape($ENV{'form.filename'});
1.2       www      1689: 
1.27      www      1690:   
1.139     albertel 1691:     unless ($fn) { 
                   1692: 	$r->log_reason($cuname.' at '.$cudom.
                   1693: 		       ' trying to publish empty filename', $r->filename); 
                   1694: 	return HTTP_NOT_FOUND;
                   1695:     } 
                   1696: 
                   1697:     ($cuname,$cudom)=
                   1698: 	&Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
                   1699:     unless (($cuname) && ($cudom)) {
                   1700: 	$r->log_reason($cuname.' at '.$cudom.
                   1701: 		       ' trying to publish file '.$ENV{'form.filename'}.
                   1702: 		       ' ('.$fn.') - not authorized', 
                   1703: 		       $r->filename); 
                   1704: 	return HTTP_NOT_ACCEPTABLE;
                   1705:     }
                   1706: 
                   1707:     unless (&Apache::lonnet::homeserver($cuname,$cudom) 
                   1708: 	    eq $r->dir_config('lonHostID')) {
                   1709: 	$r->log_reason($cuname.' at '.$cudom.
                   1710: 		       ' trying to publish file '.$ENV{'form.filename'}.
                   1711: 		       ' ('.$fn.') - not homeserver ('.
                   1712: 		       &Apache::lonnet::homeserver($cuname,$cudom).')', 
                   1713: 		       $r->filename); 
                   1714: 	return HTTP_NOT_ACCEPTABLE;
                   1715:     }
                   1716: 
                   1717:     $fn=~s/^http\:\/\/[^\/]+//;
                   1718:     $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
                   1719: 
                   1720:     my $targetdir='';
                   1721:     $docroot=$r->dir_config('lonDocRoot'); 
                   1722:     if ($1 ne $cuname) {
                   1723: 	$r->log_reason($cuname.' at '.$cudom.
                   1724: 		       ' trying to publish unowned file '.
                   1725: 		       $ENV{'form.filename'}.' ('.$fn.')', 
                   1726: 		       $r->filename); 
                   1727: 	return HTTP_NOT_ACCEPTABLE;
                   1728:     } else {
                   1729: 	$targetdir=$docroot.'/res/'.$cudom;
                   1730:     }
1.2       www      1731:                                  
                   1732:   
1.139     albertel 1733:     unless (-e $fn) { 
                   1734: 	$r->log_reason($cuname.' at '.$cudom.
                   1735: 		       ' trying to publish non-existing file '.
                   1736: 		       $ENV{'form.filename'}.' ('.$fn.')', 
                   1737: 		       $r->filename); 
                   1738: 	return HTTP_NOT_FOUND;
                   1739:     } 
1.2       www      1740: 
1.139     albertel 1741:     unless ($ENV{'form.phase'} eq 'two') {
1.11      www      1742: 
1.94      harris41 1743: # -------------------------------- File is there and owned, init lookup tables.
1.2       www      1744: 
1.139     albertel 1745: 	%addid=();
                   1746: 
                   1747: 	{
                   1748: 	    my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
                   1749: 	    while (<$fh>=~/(\w+)\s+(\w+)/) {
                   1750: 		$addid{$1}=$2;
                   1751: 	    }
                   1752: 	}
1.3       www      1753: 
1.139     albertel 1754: 	%nokey=();
1.11      www      1755: 
1.139     albertel 1756: 	{
                   1757: 	    my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
                   1758: 	    while (<$fh>) {
                   1759: 		my $word=$_;
                   1760: 		chomp($word);
                   1761: 		$nokey{$word}=1;
                   1762: 	    }
                   1763: 	}
                   1764: 
                   1765:     }
1.11      www      1766: 
1.94      harris41 1767: # ---------------------------------------------------------- Start page output.
1.2       www      1768: 
1.139     albertel 1769:     &Apache::loncommon::content_type($r,'text/html');
                   1770:     $r->send_http_header;
1.1       www      1771: 
1.139     albertel 1772:     $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
                   1773:     $r->print(&Apache::loncommon::bodytag('Resource Publication'));
1.101     www      1774: 
                   1775: 
1.139     albertel 1776:     my $thisfn=$fn;
1.95      www      1777: 
1.139     albertel 1778:     my $thistarget=$thisfn;
1.95      www      1779:       
1.139     albertel 1780:     $thistarget=~s/^\/home/$targetdir/;
                   1781:     $thistarget=~s/\/public\_html//;
1.95      www      1782: 
1.139     albertel 1783:     my $thisdistarget=$thistarget;
                   1784:     $thisdistarget=~s/^\Q$docroot\E//;
1.95      www      1785: 
1.139     albertel 1786:     my $thisdisfn=$thisfn;
                   1787:     $thisdisfn=~s/^\/home\/\Q$cuname\E\/public_html\///;
1.95      www      1788: 
1.139     albertel 1789:     if ($fn=~/\/$/) {
1.95      www      1790: # -------------------------------------------------------- This is a directory
1.139     albertel 1791: 	&publishdirectory($r,$fn,$thisdisfn);
                   1792: 	$r->print('<hr><font size="+2">'.&mt('Done').'</font><br><a href="/priv/'
                   1793: 		  .$cuname.'/'.$thisdisfn
                   1794: 		  .'">'.&mt('Return to Directory').'</a>');
1.128     www      1795: 
1.95      www      1796: 
1.139     albertel 1797:     } else {
1.94      harris41 1798: # ---------------------- Evaluate individual file, and then output information.
1.139     albertel 1799: 	$thisfn=~/\.(\w+)$/;
                   1800: 	my $thistype=$1;
                   1801: 	my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
                   1802: 	$r->print('<h2>'.&mt('Publishing').' '.
                   1803: 		  &Apache::loncommon::filedescription($thistype).' <tt>');
1.2       www      1804: 
1.139     albertel 1805: 	$r->print(<<ENDCAPTION);
1.129     www      1806: <a href='javascript:void(window.open("/~$cuname/$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
                   1807: $thisdisfn</a>
                   1808: ENDCAPTION
1.139     albertel 1809:         $r->print('</tt></h2><b>'.&mt('Target').':</b> <tt>'.
                   1810: 		  $thisdistarget.'</tt><br />');
1.27      www      1811:    
1.139     albertel 1812: 	if (($cuname ne $ENV{'user.name'})||($cudom ne $ENV{'user.domain'})) {
                   1813: 	    $r->print('<h3><font color="red">'.&mt('Co-Author').': '.
                   1814: 		      $cuname.&mt(' at ').$cudom.'</font></h3>');
                   1815: 	}
1.26      www      1816: 
1.139     albertel 1817: 	if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
                   1818: 	    $r->print(<<ENDDIFF);
1.129     www      1819: <br />
1.136     www      1820: <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"))'>
1.129     www      1821: ENDDIFF
1.139     albertel 1822:             $r->print(&mt('Diffs with Current Version').'</a><br />');
                   1823: 	}
1.11      www      1824:   
1.94      harris41 1825: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
1.2       www      1826: 
1.139     albertel 1827: 	unless ($ENV{'form.phase'} eq 'two') {
                   1828: 	    my ($outstring,$error)=&publish($thisfn,$thistarget,$thisembstyle);
                   1829: 	    $r->print('<hr />'.$outstring);
                   1830: 	} else {
                   1831: 	    $r->print('<hr />');
                   1832: 	    &phasetwo($r,$thisfn,$thistarget,$thisembstyle,$thisdistarget); 
                   1833: 	}
                   1834:     }
                   1835:     $r->print('</body></html>');
1.15      www      1836: 
1.139     albertel 1837:     return OK;
1.1       www      1838: }
                   1839: 
                   1840: 1;
                   1841: __END__
                   1842: 
1.89      matthew  1843: =pod
1.126     bowersj2 1844: 
                   1845: =back
1.66      harris41 1846: 
                   1847: =back
                   1848: 
1.89      matthew  1849: =cut
1.66      harris41 1850: 

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