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

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

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