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

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

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