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

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

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