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

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

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