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

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

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