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

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

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