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

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

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