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

1.1       www         1: # The LearningOnline Network with CAPA
                      2: # Publication Handler
1.54      albertel    3: #
1.279   ! www         4: # $Id: lonpublisher.pm,v 1.278 2012/01/29 03:08:32 raeburn 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: 
1.274     raeburn    69: Authors can only write-access the C</priv/domain/authorname/> space. 
                     70: They can copy resources into the resource area through the 
                     71: publication step, and move them back through a recover step. 
                     72: Authors do not have direct write-access to their resource space.
1.127     bowersj2   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.245     onken     121: use HTML::Entities;
                    122: use Encode::Encoder;
1.4       www       123: use Apache::lonxml;
1.27      www       124: use Apache::loncacc;
1.24      harris41  125: use DBI;
1.192     albertel  126: use Apache::lonnet;
1.65      harris41  127: use Apache::loncommon();
1.241     raeburn   128: use Apache::lonhtmlcommon;
1.89      matthew   129: use Apache::lonmysql;
1.134     www       130: use Apache::lonlocal;
1.145     albertel  131: use Apache::loncfile;
1.166     matthew   132: use LONCAPA::lonmetadata;
1.159     www       133: use Apache::lonmsg;
1.105     www       134: use vars qw(%metadatafields %metadatakeys);
1.215     albertel  135: use LONCAPA qw(:DEFAULT :match);
1.209     www       136:  
1.2       www       137: 
1.3       www       138: my %addid;
1.5       www       139: my %nokey;
1.10      www       140: 
1.12      www       141: my $docroot;
                    142: 
1.27      www       143: my $cuname;
                    144: my $cudom;
                    145: 
1.182     www       146: my $registered_cleanup;
1.183     www       147: my $modified_urls;
1.182     www       148: 
1.233     www       149: my $lock;
                    150: 
1.90      matthew   151: =pod
                    152: 
1.94      harris41  153: =item B<metaeval>
                    154: 
                    155: Evaluates a string that contains metadata.  This subroutine
                    156: stores values inside I<%metadatafields> and I<%metadatakeys>.
                    157: The hash key is a I<$unikey> corresponding to a unique id
                    158: that is descriptive of the parser location inside the XML tree.
                    159: 
                    160: Parameters:
                    161: 
                    162: =over 4
1.90      matthew   163: 
1.94      harris41  164: =item I<$metastring>
                    165: 
                    166: A string that contains metadata.
                    167: 
                    168: =back
                    169: 
                    170: Returns:
                    171: 
                    172: nothing
1.90      matthew   173: 
                    174: =cut
                    175: 
                    176: #########################################
                    177: #########################################
1.144     www       178: #
                    179: # Modifies global %metadatafields %metadatakeys 
                    180: #
                    181: 
1.7       www       182: sub metaeval {
1.140     albertel  183:     my ($metastring,$prefix)=@_;
1.7       www       184:    
1.139     albertel  185:     my $parser=HTML::LCParser->new(\$metastring);
                    186:     my $token;
                    187:     while ($token=$parser->get_token) {
                    188: 	if ($token->[0] eq 'S') {
                    189: 	    my $entry=$token->[1];
                    190: 	    my $unikey=$entry;
1.219     albertel  191: 	    next if ($entry =~ m/^(?:parameter|stores)_/);
1.139     albertel  192: 	    if (defined($token->[2]->{'package'})) { 
1.219     albertel  193: 		$unikey.="\0package\0".$token->[2]->{'package'};
1.139     albertel  194: 	    } 
                    195: 	    if (defined($token->[2]->{'part'})) { 
1.219     albertel  196: 		$unikey.="\0".$token->[2]->{'part'}; 
1.139     albertel  197: 	    }
                    198: 	    if (defined($token->[2]->{'id'})) { 
1.219     albertel  199: 		$unikey.="\0".$token->[2]->{'id'};
1.139     albertel  200: 	    } 
                    201: 	    if (defined($token->[2]->{'name'})) { 
1.219     albertel  202: 		$unikey.="\0".$token->[2]->{'name'}; 
1.139     albertel  203: 	    }
                    204: 	    foreach (@{$token->[3]}) {
                    205: 		$metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
                    206: 		if ($metadatakeys{$unikey}) {
                    207: 		    $metadatakeys{$unikey}.=','.$_;
                    208: 		} else {
                    209: 		    $metadatakeys{$unikey}=$_;
                    210: 		}
                    211: 	    }
1.140     albertel  212: 	    my $newentry=$parser->get_text('/'.$entry);
1.174     www       213: 	    if (($entry eq 'customdistributionfile') ||
                    214: 		($entry eq 'sourcerights')) {
1.140     albertel  215: 		$newentry=~s/^\s*//;
                    216: 		if ($newentry !~m|^/res|) { $newentry=$prefix.$newentry; }
                    217: 	    }
1.149     www       218: # actually store
1.162     albertel  219: 	    if ( $entry eq 'rule' && exists($metadatafields{$unikey})) {
                    220: 		$metadatafields{$unikey}.=','.$newentry;
                    221: 	    } else {
                    222: 		$metadatafields{$unikey}=$newentry;
                    223: 	    }
1.139     albertel  224: 	}
                    225:     }
1.7       www       226: }
                    227: 
1.90      matthew   228: #########################################
                    229: #########################################
                    230: 
                    231: =pod
                    232: 
1.94      harris41  233: =item B<metaread>
1.90      matthew   234: 
                    235: Read a metadata file
                    236: 
1.94      harris41  237: Parameters:
                    238: 
                    239: =over
                    240: 
                    241: =item I<$logfile>
                    242: 
                    243: File output stream to output errors and warnings to.
                    244: 
                    245: =item I<$fn>
                    246: 
                    247: File name (including path).
                    248: 
                    249: =back
                    250: 
                    251: Returns:
                    252: 
                    253: =over 4
                    254: 
                    255: =item Scalar string (if successful)
                    256: 
                    257: XHTML text that indicates successful reading of the metadata.
                    258: 
                    259: =back
                    260: 
1.90      matthew   261: =cut
                    262: 
                    263: #########################################
                    264: #########################################
1.7       www       265: sub metaread {
1.140     albertel  266:     my ($logfile,$fn,$prefix)=@_;
1.7       www       267:     unless (-e $fn) {
1.94      harris41  268: 	print($logfile 'No file '.$fn."\n");
1.271     www       269:         return '<p class="LC_warning">'
                    270:               .&mt('No file: [_1]',&Apache::loncfile::display($fn))
                    271:               .'</p>';
1.7       www       272:     }
1.94      harris41  273:     print($logfile 'Processing '.$fn."\n");
1.7       www       274:     my $metastring;
                    275:     {
1.140     albertel  276: 	my $metafh=Apache::File->new($fn);
                    277: 	$metastring=join('',<$metafh>);
1.7       www       278:     }
1.140     albertel  279:     &metaeval($metastring,$prefix);
1.271     www       280:     return '<p class="LC_info">'
                    281:           .&mt('Processed file: [_1]',&Apache::loncfile::display($fn))
                    282:           .'</p>';
1.7       www       283: }
1.12      www       284: 
1.90      matthew   285: #########################################
                    286: #########################################
                    287: 
1.101     www       288: sub coursedependencies {
                    289:     my $url=&Apache::lonnet::declutter(shift);
                    290:     $url=~s/\.meta$//;
1.215     albertel  291:     my ($adomain,$aauthor)=($url=~ m{^($match_domain)/($match_username)/});
                    292:     my $regexp=quotemeta($url);
1.101     www       293:     $regexp='___'.$regexp.'___course';
                    294:     my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
                    295: 				       $aauthor,$regexp);
                    296:     my %courses=();
                    297:     foreach (keys %evaldata) {
                    298: 	if ($_=~/^([a-zA-Z0-9]+_[a-zA-Z0-9]+)___.+___course$/) {
                    299: 	    $courses{$1}=1;
                    300:         }
                    301:     }
                    302:     return %courses;
                    303: }
                    304: #########################################
                    305: #########################################
                    306: 
                    307: 
1.90      matthew   308: =pod
                    309: 
1.94      harris41  310: =item Form-field-generating subroutines.
                    311: 
                    312: For input parameters, these subroutines take in values
                    313: such as I<$name>, I<$value> and other form field metadata.
                    314: The output (scalar string that is returned) is an XHTML
                    315: string which presents the form field (foreseeably inside
                    316: <form></form> tags).
1.90      matthew   317: 
                    318: =over 4
                    319: 
1.94      harris41  320: =item B<textfield>
1.90      matthew   321: 
1.94      harris41  322: =item B<hiddenfield>
1.90      matthew   323: 
1.94      harris41  324: =item B<selectbox>
1.90      matthew   325: 
                    326: =back
                    327: 
                    328: =cut
                    329: 
                    330: #########################################
                    331: #########################################
1.8       www       332: sub textfield {
1.240     raeburn   333:     my ($title,$name,$value,$noline)=@_;
1.141     www       334:     $value=~s/^\s+//gs;
                    335:     $value=~s/\s+$//gs;
                    336:     $value=~s/\s+/ /gs;
1.134     www       337:     $title=&mt($title);
1.192     albertel  338:     $env{'form.'.$name}=$value;
1.238     bisitz    339:     return "\n".&Apache::lonhtmlcommon::row_title($title)
                    340:            .'<input type="text" name="'.$name.'" size="80" value="'.$value.'" />'
1.240     raeburn   341:            .&Apache::lonhtmlcommon::row_closure($noline);
1.11      www       342: }
                    343: 
1.180     albertel  344: sub text_with_browse_field {
1.240     raeburn   345:     my ($title,$name,$value,$restriction,$noline)=@_;
1.180     albertel  346:     $value=~s/^\s+//gs;
                    347:     $value=~s/\s+$//gs;
                    348:     $value=~s/\s+/ /gs;
                    349:     $title=&mt($title);
1.192     albertel  350:     $env{'form.'.$name}=$value;
1.238     bisitz    351:     return "\n".&Apache::lonhtmlcommon::row_title($title)
                    352:           .'<input type="text" name="'.$name.'" size="80" value="'.$value.'" />'
                    353:           .'<br />'
                    354: 	  .'<a href="javascript:openbrowser(\'pubform\',\''.$name.'\',\''.$restriction.'\');">'
                    355:           .&mt('Select')
                    356:           .'</a>&nbsp;'
                    357: 	  .'<a href="javascript:opensearcher(\'pubform\',\''.$name.'\');">'
                    358:           .&mt('Search')
                    359:           .'</a>'
1.240     raeburn   360:           .&Apache::lonhtmlcommon::row_closure($noline);
1.180     albertel  361: }
                    362: 
1.11      www       363: sub hiddenfield {
                    364:     my ($name,$value)=@_;
1.192     albertel  365:     $env{'form.'.$name}=$value;
1.94      harris41  366:     return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
1.8       www       367: }
                    368: 
1.193     www       369: sub checkbox {
                    370:     my ($name,$text)=@_;
1.201     albertel  371:     return "\n<br /><label><input type='checkbox' name='$name' /> ".
                    372: 	&mt($text)."</label>";
1.193     www       373: }
                    374: 
1.9       www       375: sub selectbox {
1.65      harris41  376:     my ($title,$name,$value,$functionref,@idlist)=@_;
1.134     www       377:     $title=&mt($title);
1.123     albertel  378:     $value=(split(/\s*,\s*/,$value))[-1];
1.167     albertel  379:     if (defined($value)) {
1.192     albertel  380: 	$env{'form.'.$name}=$value;
1.167     albertel  381:     } else {
1.192     albertel  382: 	$env{'form.'.$name}=$idlist[0];
1.167     albertel  383:     }
1.238     bisitz    384:     my $selout="\n".&Apache::lonhtmlcommon::row_title($title)
                    385:               .'<select name="'.$name.'">';
1.65      harris41  386:     foreach (@idlist) {
1.257     bisitz    387:         $selout.='<option value="'.$_.'"';
1.65      harris41  388:         if ($_ eq $value) {
1.257     bisitz    389: 	    $selout.=' selected="selected"';
                    390:         }
                    391:         $selout.='>'.&{$functionref}($_).'</option>';
1.65      harris41  392:     }
1.238     bisitz    393:     $selout.='</select>'.&Apache::lonhtmlcommon::row_closure();
                    394:     return $selout;
1.9       www       395: }
                    396: 
1.167     albertel  397: sub select_level_form {
                    398:     my ($value,$name)=@_;
1.192     albertel  399:     $env{'form.'.$name}=$value;
                    400:     if (!defined($value)) { $env{'form.'.$name}=0; }
1.167     albertel  401:     return  &Apache::loncommon::select_level_form($value,$name);
                    402: }
1.90      matthew   403: #########################################
                    404: #########################################
                    405: 
                    406: =pod
                    407: 
1.94      harris41  408: =item B<urlfixup>
1.90      matthew   409: 
                    410: Fix up a url?  First step of publication
1.12      www       411: 
1.90      matthew   412: =cut
                    413: 
                    414: #########################################
                    415: #########################################
1.34      www       416: sub urlfixup {
1.35      www       417:     my ($url,$target)=@_;
1.39      www       418:     unless ($url) { return ''; }
1.68      albertel  419:     #javascript code needs no fixing
                    420:     if ($url =~ /^javascript:/i) { return $url; }
1.69      albertel  421:     if ($url =~ /^mailto:/i) { return $url; }
1.68      albertel  422:     #internal document links need no fixing
                    423:     if ($url =~ /^\#/) { return $url; } 
1.223     albertel  424:     my ($host)=($url=~m{(?:(?:http|https|ftp)://)*([^/]+)});
                    425:     my @lonids = &Apache::lonnet::machine_ids($host);
                    426:     if (@lonids) {
                    427: 	$url=~s{^(?:http|https|ftp)://}{};
                    428: 	$url=~s/^\Q$host\E//;
1.65      harris41  429:     }
1.223     albertel  430:     if ($url=~m{^(?:http|https|ftp)://}) { return $url; }
1.222     albertel  431:     $url=~s{\Q~$cuname\E}{res/$cudom/$cuname};
1.71      www       432:     return $url;
                    433: }
                    434: 
1.90      matthew   435: #########################################
                    436: #########################################
                    437: 
                    438: =pod
                    439: 
1.94      harris41  440: =item B<absoluteurl>
1.90      matthew   441: 
1.94      harris41  442: Currently undocumented.
1.90      matthew   443: 
                    444: =cut
1.71      www       445: 
1.90      matthew   446: #########################################
                    447: #########################################
1.71      www       448: sub absoluteurl {
                    449:     my ($url,$target)=@_;
                    450:     unless ($url) { return ''; }
1.35      www       451:     if ($target) {
                    452: 	$target=~s/\/[^\/]+$//;
                    453:        $url=&Apache::lonnet::hreflocation($target,$url);
                    454:     }
                    455:     return $url;
1.34      www       456: }
                    457: 
1.90      matthew   458: #########################################
                    459: #########################################
                    460: 
                    461: =pod
                    462: 
1.94      harris41  463: =item B<set_allow>
1.90      matthew   464: 
                    465: Currently undocumented    
                    466: 
                    467: =cut
                    468: 
                    469: #########################################
                    470: #########################################
1.81      albertel  471: sub set_allow {
                    472:     my ($allow,$logfile,$target,$tag,$oldurl)=@_;
                    473:     my $newurl=&urlfixup($oldurl,$target);
                    474:     my $return_url=$oldurl;
                    475:     print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
                    476:     if ($newurl ne $oldurl) {
                    477: 	$return_url=$newurl;
                    478: 	print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
                    479:     }
                    480:     if (($newurl !~ /^javascript:/i) &&
                    481: 	($newurl !~ /^mailto:/i) &&
1.220     albertel  482: 	($newurl !~ /^(?:http|https|ftp):/i) &&
1.81      albertel  483: 	($newurl !~ /^\#/)) {
                    484: 	$$allow{&absoluteurl($newurl,$target)}=1;
                    485:     }
1.218     raeburn   486:     return $return_url;
1.81      albertel  487: }
                    488: 
1.90      matthew   489: #########################################
                    490: #########################################
                    491: 
                    492: =pod
                    493: 
1.94      harris41  494: =item B<get_subscribed_hosts>
1.90      matthew   495: 
                    496: Currently undocumented    
                    497: 
                    498: =cut
                    499: 
                    500: #########################################
                    501: #########################################
1.85      albertel  502: sub get_subscribed_hosts {
                    503:     my ($target)=@_;
                    504:     my @subscribed;
                    505:     my $filename;
                    506:     $target=~/(.*)\/([^\/]+)$/;
                    507:     my $srcf=$2;
                    508:     opendir(DIR,$1);
1.225     albertel  509:     # cycle through listed files, subscriptions used to exist
                    510:     # as "filename.lonid"
1.85      albertel  511:     while ($filename=readdir(DIR)) {
1.216     albertel  512: 	if ($filename=~/\Q$srcf\E\.($match_lonid)$/) {
1.85      albertel  513: 	    my $subhost=$1;
1.225     albertel  514: 	    if (($subhost ne 'meta' 
                    515: 		 && $subhost ne 'subscription' 
                    516: 		 && $subhost ne 'meta.subscription'
                    517: 		 && $subhost ne 'tmp') &&
1.98      www       518:                 ($subhost ne $Apache::lonnet::perlvar{'lonHostID'})) {
1.85      albertel  519: 		push(@subscribed,$subhost);
                    520: 	    }
                    521: 	}
                    522:     }
                    523:     closedir(DIR);
                    524:     my $sh;
                    525:     if ( $sh=Apache::File->new("$target.subscription") ) {
                    526: 	while (my $subline=<$sh>) {
1.216     albertel  527: 	    if ($subline =~ /^($match_lonid):/) { 
1.98      www       528:                 if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) { 
                    529:                    push(@subscribed,$1);
                    530: 	        }
1.85      albertel  531: 	    }
                    532: 	}
                    533:     }
                    534:     return @subscribed;
                    535: }
                    536: 
1.86      albertel  537: 
1.90      matthew   538: #########################################
                    539: #########################################
                    540: 
                    541: =pod
                    542: 
1.94      harris41  543: =item B<get_max_ids_indices>
1.90      matthew   544: 
                    545: Currently undocumented    
                    546: 
                    547: =cut
                    548: 
                    549: #########################################
                    550: #########################################
1.86      albertel  551: sub get_max_ids_indices {
                    552:     my ($content)=@_;
                    553:     my $maxindex=10;
                    554:     my $maxid=10;
                    555:     my $needsfixup=0;
1.106     albertel  556:     my $duplicateids=0;
                    557: 
                    558:     my %allids;
                    559:     my %duplicatedids;
1.86      albertel  560: 
                    561:     my $parser=HTML::LCParser->new($content);
1.207     albertel  562:     $parser->xml_mode(1);
1.86      albertel  563:     my $token;
                    564:     while ($token=$parser->get_token) {
                    565: 	if ($token->[0] eq 'S') {
                    566: 	    my $counter;
                    567: 	    if ($counter=$addid{$token->[1]}) {
                    568: 		if ($counter eq 'id') {
1.186     albertel  569: 		    if (defined($token->[2]->{'id'}) &&
                    570: 			$token->[2]->{'id'} !~ /^\s*$/) {
1.86      albertel  571: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
1.106     albertel  572: 			if (exists($allids{$token->[2]->{'id'}})) {
                    573: 			    $duplicateids=1;
                    574: 			    $duplicatedids{$token->[2]->{'id'}}=1;
                    575: 			} else {
                    576: 			    $allids{$token->[2]->{'id'}}=1;
                    577: 			}
1.86      albertel  578: 		    } else {
                    579: 			$needsfixup=1;
                    580: 		    }
                    581: 		} else {
1.186     albertel  582: 		    if (defined($token->[2]->{'index'}) &&
                    583: 			$token->[2]->{'index'} !~ /^\s*$/) {
1.86      albertel  584: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
                    585: 		    } else {
                    586: 			$needsfixup=1;
                    587: 		    }
                    588: 		}
                    589: 	    }
                    590: 	}
                    591:     }
1.106     albertel  592:     return ($needsfixup,$maxid,$maxindex,$duplicateids,
                    593: 	    (keys(%duplicatedids)));
1.86      albertel  594: }
                    595: 
1.90      matthew   596: #########################################
                    597: #########################################
                    598: 
                    599: =pod
                    600: 
1.94      harris41  601: =item B<get_all_text_unbalanced>
1.90      matthew   602: 
                    603: Currently undocumented    
                    604: 
                    605: =cut
                    606: 
                    607: #########################################
                    608: #########################################
1.87      albertel  609: sub get_all_text_unbalanced {
                    610:     #there is a copy of this in lonxml.pm
                    611:     my($tag,$pars)= @_;
                    612:     my $token;
                    613:     my $result='';
                    614:     $tag='<'.$tag.'>';
                    615:     while ($token = $$pars[-1]->get_token) {
                    616: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
                    617: 	    $result.=$token->[1];
                    618: 	} elsif ($token->[0] eq 'PI') {
                    619: 	    $result.=$token->[2];
                    620: 	} elsif ($token->[0] eq 'S') {
                    621: 	    $result.=$token->[4];
                    622: 	} elsif ($token->[0] eq 'E')  {
                    623: 	    $result.=$token->[2];
                    624: 	}
1.177     albertel  625: 	if ($result =~ /\Q$tag\E/s) {
1.176     albertel  626: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
1.88      albertel  627: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
                    628: 	    #&Apache::lonnet::logthis('Result is :'.$1);
1.176     albertel  629: 	    $redo=$tag.$redo;
1.87      albertel  630: 	    push (@$pars,HTML::LCParser->new(\$redo));
                    631: 	    $$pars[-1]->xml_mode('1');
                    632: 	    last;
                    633: 	}
                    634:     }
                    635:     return $result
                    636: }
                    637: 
1.90      matthew   638: #########################################
                    639: #########################################
                    640: 
                    641: =pod
                    642: 
1.94      harris41  643: =item B<fix_ids_and_indices>
1.90      matthew   644: 
                    645: Currently undocumented    
                    646: 
                    647: =cut
                    648: 
                    649: #########################################
                    650: #########################################
1.87      albertel  651: #Arguably this should all be done as a lonnet::ssi instead
1.86      albertel  652: sub fix_ids_and_indices {
                    653:     my ($logfile,$source,$target)=@_;
                    654: 
                    655:     my %allow;
                    656:     my $content;
                    657:     {
                    658: 	my $org=Apache::File->new($source);
                    659: 	$content=join('',<$org>);
                    660:     }
                    661: 
1.106     albertel  662:     my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
                    663: 	&get_max_ids_indices(\$content);
1.86      albertel  664: 
1.106     albertel  665:     print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
                    666: 			   join(', ',@duplicatedids));
                    667:     if ($duplicateids) {
                    668: 	print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
1.226     albertel  669: 	my $outstring='<span class="LC_error">'.&mt('Unable to publish file, it contains duplicated ID(s), ID(s) need to be unique. The duplicated ID(s) are').': '.join(', ',@duplicatedids).'</span>';
1.106     albertel  670: 	return ($outstring,1);
                    671:     }
1.86      albertel  672:     if ($needsfixup) {
                    673: 	print $logfile "Needs ID and/or index fixup\n".
                    674: 	    "Max ID   : $maxid (min 10)\n".
                    675:                 "Max Index: $maxindex (min 10)\n";
                    676:     }
                    677:     my $outstring='';
1.236     www       678:     my $responsecounter=1;
1.86      albertel  679:     my @parser;
                    680:     $parser[0]=HTML::LCParser->new(\$content);
                    681:     $parser[-1]->xml_mode(1);
                    682:     my $token;
                    683:     while (@parser) {
                    684: 	while ($token=$parser[-1]->get_token) {
                    685: 	    if ($token->[0] eq 'S') {
                    686: 		my $counter;
                    687: 		my $tag=$token->[1];
                    688: 		my $lctag=lc($tag);
                    689: 		if ($lctag eq 'allow') {
                    690: 		    $allow{$token->[2]->{'src'}}=1;
                    691: 		    next;
                    692: 		}
1.202     albertel  693: 		if ($lctag eq 'base') { next; }
1.236     www       694:                 if (($lctag eq 'part') || ($lctag eq 'problem')) {
                    695:                     $responsecounter=0;
                    696:                 }
                    697:                 if ($lctag=~/response$/) { $responsecounter++; }
1.249     www       698:                 if ($lctag eq 'import') { $responsecounter++; }
1.86      albertel  699: 		my %parms=%{$token->[2]};
                    700: 		$counter=$addid{$tag};
                    701: 		if (!$counter) { $counter=$addid{$lctag}; }
                    702: 		if ($counter) {
                    703: 		    if ($counter eq 'id') {
1.186     albertel  704: 			unless (defined($parms{'id'}) &&
                    705: 				$parms{'id'}!~/^\s*$/) {
1.86      albertel  706: 			    $maxid++;
                    707: 			    $parms{'id'}=$maxid;
1.205     albertel  708: 			    print $logfile 'ID(new) : '.$tag.':'.$maxid."\n";
                    709: 			} else {
                    710: 			    print $logfile 'ID(kept): '.$tag.':'.$parms{'id'}."\n";
1.86      albertel  711: 			}
                    712: 		    } elsif ($counter eq 'index') {
1.186     albertel  713: 			unless (defined($parms{'index'}) &&
                    714: 				$parms{'index'}!~/^\s*$/) {
1.86      albertel  715: 			    $maxindex++;
                    716: 			    $parms{'index'}=$maxindex;
                    717: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
                    718: 			}
                    719: 		    }
                    720: 		}
1.203     www       721:                 unless ($parms{'type'} eq 'zombie') {
                    722: 		    foreach my $type ('src','href','background','bgimg') {
                    723: 			foreach my $key (keys(%parms)) {
                    724: 			    if ($key =~ /^$type$/i) {
                    725: 				$parms{$key}=&set_allow(\%allow,$logfile,
                    726: 							$target,$tag,
                    727: 							$parms{$key});
                    728: 			    }
1.86      albertel  729: 			}
                    730: 		    }
                    731: 		}
                    732: 		# probably a <randomlabel> image type <label>
1.135     albertel  733: 		# or a <image> tag inside <imageresponse>
                    734: 		if (($lctag eq 'label' && defined($parms{'description'}))
                    735: 		    ||
                    736: 		    ($lctag eq 'image')) {
1.86      albertel  737: 		    my $next_token=$parser[-1]->get_token();
                    738: 		    if ($next_token->[0] eq 'T') {
1.218     raeburn   739:                         $next_token->[1] =~ s/[\n\r\f]+//g;
1.86      albertel  740: 			$next_token->[1]=&set_allow(\%allow,$logfile,
                    741: 						    $target,$tag,
                    742: 						    $next_token->[1]);
                    743: 		    }
                    744: 		    $parser[-1]->unget_token($next_token);
                    745: 		}
                    746: 		if ($lctag eq 'applet') {
                    747: 		    my $codebase='';
1.148     albertel  748: 		    my $havecodebase=0;
                    749: 		    foreach my $key (keys(%parms)) {
                    750: 			if (lc($key) eq 'codebase') { 
                    751: 			    $codebase=$parms{$key};
                    752: 			    $havecodebase=1; 
                    753: 			}
                    754: 		    }
                    755: 		    if ($havecodebase) {
                    756: 			my $oldcodebase=$codebase;
1.86      albertel  757: 			unless ($oldcodebase=~/\/$/) {
                    758: 			    $oldcodebase.='/';
                    759: 			}
                    760: 			$codebase=&urlfixup($oldcodebase,$target);
                    761: 			$codebase=~s/\/$//;    
                    762: 			if ($codebase ne $oldcodebase) {
                    763: 			    $parms{'codebase'}=$codebase;
                    764: 			    print $logfile 'URL codebase: '.$tag.':'.
                    765: 				$oldcodebase.' - '.
                    766: 				    $codebase."\n";
                    767: 			}
                    768: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
                    769: 		    } else {
1.148     albertel  770: 			foreach my $key (keys(%parms)) {
                    771: 			    if ($key =~ /(archive|code|object)/i) {
                    772: 				my $oldurl=$parms{$key};
1.86      albertel  773: 				my $newurl=&urlfixup($oldurl,$target);
                    774: 				$newurl=~s/\/[^\/]+$/\/\*/;
1.148     albertel  775: 				print $logfile 'Allow: applet '.lc($key).':'.
                    776: 				    $oldurl.' allows '.$newurl."\n";
1.86      albertel  777: 				$allow{&absoluteurl($newurl,$target)}=1;
                    778: 			    }
                    779: 			}
                    780: 		    }
                    781: 		}
                    782: 		my $newparmstring='';
                    783: 		my $endtag='';
                    784: 		foreach (keys %parms) {
                    785: 		    if ($_ eq '/') {
                    786: 			$endtag=' /';
                    787: 		    } else { 
                    788: 			my $quote=($parms{$_}=~/\"/?"'":'"');
                    789: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
                    790: 		    }
                    791: 		}
                    792: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
                    793: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
1.235     www       794: 		if ($lctag eq 'm' || $lctag eq 'script' || $lctag eq 'answer' 
1.131     albertel  795:                     || $lctag eq 'display' || $lctag eq 'tex') {
1.130     albertel  796: 		    $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
1.87      albertel  797: 		}
1.86      albertel  798: 	    } elsif ($token->[0] eq 'E') {
                    799: 		if ($token->[2]) {
                    800: 		    unless ($token->[1] eq 'allow') {
                    801: 			$outstring.='</'.$token->[1].'>';
                    802: 		    }
1.236     www       803:                 }
                    804:                 if ((($token->[1] eq 'part') || ($token->[1] eq 'problem'))
                    805:                     && (!$responsecounter)) {
1.239     bisitz    806:                     my $outstring='<span class="LC_error">'.&mt('Found [_1] without responses. This resource cannot be published.',$token->[1]).'</span>';
1.236     www       807:                     return ($outstring,1);
                    808:                 }
1.86      albertel  809: 	    } else {
                    810: 		$outstring.=$token->[1];
                    811: 	    }
                    812: 	}
                    813: 	pop(@parser);
                    814:     }
                    815: 
                    816:     if ($needsfixup) {
                    817: 	print $logfile "End of ID and/or index fixup\n".
                    818: 	    "Max ID   : $maxid (min 10)\n".
                    819: 		"Max Index: $maxindex (min 10)\n";
                    820:     } else {
                    821: 	print $logfile "Does not need ID and/or index fixup\n";
                    822:     }
                    823: 
1.106     albertel  824:     return ($outstring,0,%allow);
1.86      albertel  825: }
                    826: 
1.89      matthew   827: #########################################
                    828: #########################################
                    829: 
                    830: =pod
                    831: 
1.94      harris41  832: =item B<store_metadata>
1.89      matthew   833: 
                    834: Store the metadata in the metadata table in the loncapa database.
                    835: Uses lonmysql to access the database.
                    836: 
                    837: Inputs: \%metadata
                    838: 
                    839: Returns: (error,status).  error is undef on success, status is undef on error.
                    840: 
                    841: =cut
                    842: 
                    843: #########################################
                    844: #########################################
                    845: sub store_metadata {
1.151     www       846:     my %metadata = @_;
1.89      matthew   847:     my $error;
                    848:     # Determine if the table exists
                    849:     my $status = &Apache::lonmysql::check_table('metadata');
                    850:     if (! defined($status)) {
1.246     bisitz    851:         $error='<span class="LC_error">'
                    852:               .&mt('WARNING: Cannot connect to database!')
                    853:               .'</span>';
1.89      matthew   854:         &Apache::lonnet::logthis($error);
                    855:         return ($error,undef);
                    856:     }
                    857:     if ($status == 0) {
                    858:         # It would be nice to actually create the table....
1.246     bisitz    859:         $error ='<span class="LC_error">'
                    860:                .&mt('WARNING: The metadata table does not exist in the LON-CAPA database!')
                    861:                .'</span>';
1.89      matthew   862:         &Apache::lonnet::logthis($error);
                    863:         return ($error,undef);
                    864:     }
1.172     matthew   865:     my $dbh = &Apache::lonmysql::get_dbh();
1.237     www       866:     if (($metadata{'obsolete'}) || ($metadata{'copyright'} eq 'priv')) {
1.172     matthew   867:         # remove this entry
1.228     albertel  868: 	my $delitem = 'url = '.$dbh->quote($metadata{'url'});
                    869: 	$status = &LONCAPA::lonmetadata::delete_metadata($dbh,undef,$delitem);
                    870:                                                        
1.152     www       871:     } else {
1.213     albertel  872:         $status = &LONCAPA::lonmetadata::update_metadata($dbh,undef,undef,
1.172     matthew   873:                                                          \%metadata);
1.152     www       874:     }
1.172     matthew   875:     if (defined($status) && $status ne '') {
1.246     bisitz    876:         $error='<span class="LC_error">'
1.248     raeburn   877:               .&mt('Error occurred saving new values in metadata table in LON-CAPA database!')
1.246     bisitz    878:               .'</span>';
1.89      matthew   879:         &Apache::lonnet::logthis($error);
1.172     matthew   880:         &Apache::lonnet::logthis($status);
1.89      matthew   881:         return ($error,undef);
                    882:     }
1.213     albertel  883:     return (undef,'success');
1.89      matthew   884: }
                    885: 
1.142     www       886: 
1.185     www       887: # ========================================== Parse file for errors and warnings
                    888: 
                    889: sub checkonthis {
                    890:     my ($r,$source)=@_;
1.187     www       891:     my $uri=&Apache::lonnet::hreflocation($source);
                    892:     $uri=~s/\/$//;
1.190     albertel  893:     my $result=&Apache::lonnet::ssi_body($uri,
                    894: 					 ('grade_target'=>'web',
                    895: 					  'return_only_error_and_warning_counts' => 1));
                    896:     my ($errorcount,$warningcount)=split(':',$result);
1.187     www       897:     if (($errorcount) || ($warningcount)) {
1.242     bisitz    898:         $r->print('<h3>'.&mt('Warnings and Errors').'</h3>');
                    899:         $r->print('<tt>'.$uri.'</tt>:');
                    900:         $r->print('<ul>');
                    901:         if ($warningcount) {
                    902:             $r->print('<li><div class="LC_warning">'
                    903:                      .&mt('[quant,_1,warning]',$warningcount)
                    904:                      .'</div></li>');
                    905:         }
                    906:         if ($errorcount) {
                    907:             $r->print('<li><div class="LC_error">'
                    908:                      .&mt('[quant,_1,error]',$errorcount)
                    909:                      .' <img src="/adm/lonMisc/bomb.gif" />'
                    910:                      .'</div></li>');
                    911:         }
                    912:         $r->print('</ul>');
1.185     www       913:     } else {
1.190     albertel  914: 	#$r->print('<font color="green">'.&mt('ok').'</font>');
1.185     www       915:     }
                    916:     $r->rflush();
1.187     www       917:     return ($warningcount,$errorcount);
1.185     www       918: }
                    919: 
1.142     www       920: # ============================================== Parse file itself for metadata
1.144     www       921: #
                    922: # parses a file with target meta, sets global %metadatafields %metadatakeys 
1.142     www       923: 
                    924: sub parseformeta {
                    925:     my ($source,$style)=@_;
1.143     www       926:     my $allmeta='';
1.142     www       927:     if (($style eq 'ssi') || ($style eq 'prv')) {
                    928: 	my $dir=$source;
                    929: 	$dir=~s-/[^/]*$--;
                    930: 	my $file=$source;
                    931: 	$file=(split('/',$file))[-1];
                    932:         $source=&Apache::lonnet::hreflocation($dir,$file);
1.143     www       933: 	$allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
1.142     www       934:         &metaeval($allmeta);
                    935:     }
1.143     www       936:     return $allmeta;
1.142     www       937: }
                    938: 
1.90      matthew   939: #########################################
                    940: #########################################
                    941: 
                    942: =pod
                    943: 
1.94      harris41  944: =item B<publish>
                    945: 
                    946: This is the workhorse function of this module.  This subroutine generates
                    947: backup copies, performs any automatic processing (prior to publication,
                    948: especially for rat and ssi files),
1.90      matthew   949: 
1.113     albertel  950: Returns a 2 element array, the first is the string to be shown to the
1.248     raeburn   951: user, the second is an error code, either 1 (an error occurred) or 0
1.113     albertel  952: (no error occurred)
                    953: 
1.94      harris41  954: I<Additional documentation needed.>
1.90      matthew   955: 
                    956: =cut
                    957: 
                    958: #########################################
                    959: #########################################
1.2       www       960: sub publish {
1.50      www       961: 
1.97      www       962:     my ($source,$target,$style,$batch)=@_;
1.2       www       963:     my $logfile;
1.4       www       964:     my $scrout='';
1.23      www       965:     my $allmeta='';
                    966:     my $content='';
1.36      www       967:     my %allow=();
1.4       www       968: 
1.2       www       969:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1.226     albertel  970: 	return ('<span class="LC_error">'.&mt('No write permission to user directory, FAIL').'</span>',1);
1.2       www       971:     }
                    972:     print $logfile 
1.211     albertel  973: "\n\n================= Publish ".localtime()." Phase One  ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
1.2       www       974: 
1.119     www       975:     if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
1.3       www       976: # ------------------------------------------------------- This needs processing
1.4       www       977: 
                    978: # ----------------------------------------------------------------- Backup Copy
1.3       www       979: 	my $copyfile=$source.'.save';
1.13      www       980:         if (copy($source,$copyfile)) {
1.3       www       981: 	    print $logfile "Copied original file to ".$copyfile."\n";
                    982:         } else {
1.13      www       983: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
1.239     bisitz    984: 	    return ("<span class=\"LC_error\">".&mt("Failed to write backup copy, [_1], FAIL",$1)."</span>",1);
1.3       www       985:         }
1.4       www       986: # ------------------------------------------------------------- IDs and indices
1.86      albertel  987: 	
1.106     albertel  988: 	my ($outstring,$error);
                    989: 	($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
                    990: 							$target);
1.113     albertel  991: 	if ($error) { return ($outstring,$error); }
1.36      www       992: # ------------------------------------------------------------ Construct Allows
1.62      www       993:     
1.246     bisitz    994:         my $outdep=''; # Collect dependencies output data
1.62      www       995:         my $allowstr='';
1.232     raeburn   996:         foreach my $thisdep (sort(keys(%allow))) {
1.73      albertel  997: 	   if ($thisdep !~ /[^\s]/) { next; }
1.231     www       998:            if ($thisdep =~/\$/) {
1.246     bisitz    999:               $outdep.='<div class="LC_warning">'
1.232     raeburn  1000:                        .&mt('The resource depends on another resource with variable filename, i.e., [_1].','<tt>'.$thisdep.'</tt>').'<br />'
                   1001:                        .&mt('You likely need to explicitly allow access to all possible dependencies using the [_1]-tag.','<tt>&lt;allow&gt;</tt>')
1.246     bisitz   1002:                        ."</div>\n";
1.231     www      1003:            }
1.62      www      1004:            unless ($style eq 'rat') { 
                   1005:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
                   1006: 	   }
1.246     bisitz   1007:           $outdep.='<div>';
1.231     www      1008:            if ($thisdep!~/[\*\$]/ && $thisdep!~m|^/adm/|) {
1.246     bisitz   1009: 	       $outdep.='<a href="'.$thisdep.'">';
1.44      www      1010:            }
1.246     bisitz   1011:            $outdep.='<tt>'.$thisdep.'</tt>';
1.231     www      1012:            if ($thisdep!~/[\*\$]/ && $thisdep!~m|^/adm/|) {
1.246     bisitz   1013: 	       $outdep.='</a>';
1.59      www      1014:                if (
                   1015:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   1016:                                             $thisdep.'.meta') eq '-1') {
1.246     bisitz   1017: 		   $outdep.= ' - <span class="LC_error">'.&mt('Currently not available').
1.226     albertel 1018: 		       '</span>';
1.59      www      1019:                } else {
1.279   ! www      1020: #
        !          1021: # Store the fact that the dependency has been used by the target file
        !          1022: # Unfortunately, usage is erroneously named sequsage in lonmeta.pm
        !          1023: # The translation happens in lonmetadata.pm
        !          1024: #
1.59      www      1025:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
                   1026:                              &Apache::lonnet::declutter($thisdep).'___usage'
                   1027:                                  => time);
1.215     albertel 1028:                    $thisdep=~m{^/res/($match_domain)/($match_username)/};
1.59      www      1029:                    if ((defined($1)) && (defined($2))) {
1.92      albertel 1030:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
                   1031: 					   $1,$2);
1.59      www      1032: 		   }
                   1033: 	       }
1.44      www      1034:            }
1.246     bisitz   1035:            $outdep.='</div><br />';
                   1036:         }
                   1037: 
                   1038:         if ($outdep) {
                   1039:             $scrout.='<h3>'.&mt('Dependencies').'</h3>'
                   1040:                     .$outdep
1.65      harris41 1041:         }
1.175     albertel 1042:         $outstring=~s/\n*(\<\/[^\>]+\>[^<]*)$/$allowstr\n$1\n/s;
1.62      www      1043: 
1.94      harris41 1044: # ------------------------------------------------------------- Write modified.
1.37      www      1045: 
1.4       www      1046:         {
                   1047:           my $org;
                   1048:           unless ($org=Apache::File->new('>'.$source)) {
                   1049:              print $logfile "No write permit to $source\n";
1.226     albertel 1050:              return ('<span class="LC_error">'.&mt('No write permission to').
1.136     www      1051: 		     ' '.$source.
1.226     albertel 1052: 		     ', '.&mt('FAIL').'</span>',1);
1.4       www      1053: 	  }
1.94      harris41 1054:           print($org $outstring);
1.4       www      1055:         }
                   1056: 	  $content=$outstring;
1.34      www      1057: 
1.37      www      1058:     }
1.94      harris41 1059: # -------------------------------------------- Initial step done, now metadata.
1.7       www      1060: 
1.94      harris41 1061: # --------------------------------------- Storage for metadata keys and fields.
1.144     www      1062: # these are globals
                   1063: #
1.8       www      1064:      %metadatafields=();
                   1065:      %metadatakeys=();
                   1066:      
                   1067:      my %oldparmstores=();
1.44      www      1068:      
1.97      www      1069:     unless ($batch) {
1.254     bisitz   1070:      $scrout.='<h3>'.&mt('Metadata').' ' .
1.239     bisitz   1071:        &Apache::loncommon::help_open_topic("Metadata_Description")
1.84      bowersj2 1072:        . '</h3>';
1.97      www      1073:     }
1.7       www      1074: 
                   1075: # ------------------------------------------------ First, check out environment
1.195     www      1076:      if ((!(-e $source.'.meta')) || ($env{'form.forceoverride'})) {
1.192     albertel 1077:         $metadatafields{'author'}=$env{'environment.firstname'}.' '.
                   1078: 	                          $env{'environment.middlename'}.' '.
                   1079: 		                  $env{'environment.lastname'}.' '.
                   1080: 		                  $env{'environment.generation'};
1.8       www      1081:         $metadatafields{'author'}=~s/\s+/ /g;
                   1082:         $metadatafields{'author'}=~s/\s+$//;
1.211     albertel 1083:         $metadatafields{'owner'}=$cuname.':'.$cudom;
1.7       www      1084: 
                   1085: # ------------------------------------------------ Check out directory hierachy
                   1086: 
                   1087:         my $thisdisfn=$source;
                   1088: 
1.269     www      1089:         $thisdisfn=~s/^\Q$docroot\E\/priv\/\Q$cudom\E\/\Q$cuname\E\///;
                   1090:         my @urlparts=('.',split(/\//,$thisdisfn));
1.7       www      1091:         $#urlparts--;
                   1092: 
1.269     www      1093:         my $currentpath=$docroot.'/priv/'.$cudom.'/'.$cuname.'/';
1.7       www      1094: 
1.140     albertel 1095: 	my $prefix='../'x($#urlparts);
1.269     www      1096:         foreach my $subdir (@urlparts) {
                   1097: 	    $currentpath.=$subdir.'/';
1.140     albertel 1098:             $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
                   1099: 	    $prefix=~s|^\.\./||;
1.65      harris41 1100:         }
1.185     www      1101: 
1.149     www      1102: # ----------------------------------------------------------- Parse file itself
                   1103: # read %metadatafields from file itself
                   1104:  
                   1105: 	$allmeta=&parseformeta($source,$style);
1.7       www      1106: 
                   1107: # ------------------- Clear out parameters and stores (there should not be any)
                   1108: 
1.65      harris41 1109:         foreach (keys %metadatafields) {
1.7       www      1110: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                   1111: 		delete $metadatafields{$_};
                   1112:             }
1.65      harris41 1113:         }
1.7       www      1114: 
1.8       www      1115:     } else {
1.7       www      1116: # ---------------------- Read previous metafile, remember parameters and stores
                   1117: 
                   1118:         $scrout.=&metaread($logfile,$source.'.meta');
                   1119: 
1.65      harris41 1120:         foreach (keys %metadatafields) {
1.7       www      1121: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                   1122:                 $oldparmstores{$_}=1;
                   1123: 		delete $metadatafields{$_};
                   1124:             }
1.65      harris41 1125:         }
1.195     www      1126: # ------------------------------------------------------------- Save some stuff
                   1127:         my %savemeta=();
                   1128:         foreach ('title') {
1.267     www      1129:             if ($metadatafields{$_}) { $savemeta{$_}=$metadatafields{$_}; }
1.195     www      1130: 	}
1.161     albertel 1131: # ------------------------------------------ See if anything new in file itself
                   1132:  
                   1133: 	$allmeta=&parseformeta($source,$style);
1.195     www      1134: # ----------------------------------------------------------- Restore the stuff
                   1135:         foreach (keys %savemeta) {
                   1136: 	    $metadatafields{$_}=$savemeta{$_};
                   1137: 	}
1.144     www      1138:    }
1.7       www      1139: 
1.144     www      1140:        
1.7       www      1141: # ---------------- Find and document discrepancies in the parameters and stores
                   1142: 
1.116     albertel 1143:     my $chparms='';
                   1144:     foreach (sort keys %metadatafields) {
                   1145: 	if (($_=~/^parameter/) || ($_=~/^stores/)) {
                   1146: 	    unless ($_=~/\.\w+$/) { 
                   1147: 		unless ($oldparmstores{$_}) {
1.219     albertel 1148: 		    my $disp_key = $_;
                   1149: 		    $disp_key =~ tr/\0/_/;
                   1150: 		    print $logfile ('New: '.$disp_key."\n");
                   1151: 		    $chparms .= $disp_key.' ';
1.116     albertel 1152: 		}
                   1153: 	    }
                   1154: 	}
                   1155:     }
                   1156:     if ($chparms) {
1.224     albertel 1157: 	$scrout.='<p><b>'.&mt('New parameters or saved values').
1.136     www      1158: 	    ':</b> '.$chparms.'</p>';
1.116     albertel 1159:     }
1.7       www      1160: 
1.116     albertel 1161:     $chparms='';
                   1162:     foreach (sort keys %oldparmstores) {
                   1163: 	if (($_=~/^parameter/) || ($_=~/^stores/)) {
                   1164: 	    unless (($metadatafields{$_.'.name'}) ||
                   1165: 		    ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
1.219     albertel 1166: 		my $disp_key = $_;
                   1167: 		$disp_key =~ tr/\0/_/;
                   1168: 		print $logfile ('Obsolete: '.$disp_key."\n");
                   1169: 		$chparms.=$disp_key.' ';
1.116     albertel 1170: 	    }
                   1171: 	}
                   1172:     }
                   1173:     if ($chparms) {
1.258     bisitz   1174:         $scrout.='<p><b>'.&mt('Obsolete parameters or saved values').':</b> '
                   1175: 	        .$chparms.'</p>'
                   1176:                 .'<p class="LC_warning"><b>'.&mt('Warning!').'</b><br />'
                   1177:                 .&mt('If this resource is in active use, student performance data from the previous version may become inaccessible.')
                   1178:                 .'</p><hr />';
1.116     albertel 1179:     }
1.229     www      1180:     if ($metadatafields{'copyright'} eq 'priv') {
1.258     bisitz   1181:         $scrout.='<p class="LC_warning"><b>'.&mt('Warning!').'</b><br />'
                   1182:                 .&mt('Copyright/distribution option "Private" is no longer supported. Select another option from below. Consider "Custom Rights" for maximum control over the usage of your resource.')
                   1183:                 .'</p><hr />';
1.229     www      1184:     }
1.37      www      1185: 
1.8       www      1186: # ------------------------------------------------------- Now have all metadata
1.5       www      1187: 
1.116     albertel 1188:     my %keywords=();
1.97      www      1189:         
1.116     albertel 1190:     if (length($content)<500000) {
                   1191: 	my $textonly=$content;
                   1192: 	$textonly=~s/\<script[^\<]+\<\/script\>//g;
                   1193: 	$textonly=~s/\<m\>[^\<]+\<\/m\>//g;
                   1194: 	$textonly=~s/\<[^\>]*\>//g;
1.245     onken    1195: 
                   1196:         #this is a work simplification for german authors for present
                   1197:         $textonly=HTML::Entities::decode($textonly);           #decode HTML-character
                   1198:         $textonly=Encode::Encoder::encode('utf8', $textonly);  #encode to perl internal unicode
                   1199:         $textonly=~tr/A-ZÜÄÖ/a-züäö/;      #add lowercase rule for german "Umlaute"
                   1200:         $textonly=~s/[\$\&][a-z]\w*//g;
                   1201:         $textonly=~s/[^a-z^ü^ä^ö^ß\s]//g;  #dont delete german "Umlaute"
                   1202: 
                   1203:         foreach ($textonly=~m/[^\s]+/g) {  #match all but whitespaces
                   1204:             unless ($nokey{$_}) {
                   1205:                 $keywords{$_}=1;
                   1206:             }
                   1207:         }
                   1208: 
                   1209: 
1.116     albertel 1210:     }
1.97      www      1211:             
1.168     www      1212:     foreach my $addkey (split(/[\"\'\,\;]/,$metadatafields{'keywords'})) {
                   1213: 	$addkey=~s/\s+/ /g;
                   1214: 	$addkey=~s/^\s//;
                   1215: 	$addkey=~s/\s$//;
                   1216: 	if ($addkey=~/\w/) {
                   1217: 	    $keywords{$addkey}=1;
                   1218: 	}
1.116     albertel 1219:     }
1.97      www      1220: # --------------------------------------------------- Now we also have keywords
                   1221: # =============================================================================
1.167     albertel 1222: # interactive mode html goes into $intr_scrout
                   1223: # batch mode throws away this HTML
                   1224: # additionally all of the field functions have a by product of setting
1.192     albertel 1225: #   $env{'from.'..} so that it can be used by the phase two handler in
1.167     albertel 1226: #    batch mode
                   1227: 
1.239     bisitz   1228:     my $intr_scrout.='<br />'
1.238     bisitz   1229:                     .'<form name="pubform" action="/adm/publish" method="post">';
                   1230:     unless ($env{'form.makeobsolete'}) {
1.246     bisitz   1231:        $intr_scrout.='<p class="LC_warning">'
1.239     bisitz   1232:                     .&mt('Searching for your resource will be based on the following metadata. Please provide as much data as possible.')
                   1233:                     .'</p>'
                   1234:                     .'<p><input type="submit" value="'
1.238     bisitz   1235:                     .&mt('Finalize Publication')
1.271     www      1236:                     .'" /> <a href="'.&Apache::loncfile::url($source).'">'.&mt('Cancel').'</a></p>';
1.238     bisitz   1237:     }
1.239     bisitz   1238:     $intr_scrout.=&Apache::lonhtmlcommon::start_pick_box();
1.238     bisitz   1239:     $intr_scrout.=
1.167     albertel 1240: 	&hiddenfield('phase','two').
1.192     albertel 1241: 	&hiddenfield('filename',$env{'form.filename'}).
1.209     www      1242: 	&hiddenfield('allmeta',&escape($allmeta)).
1.194     www      1243: 	&hiddenfield('dependencies',join(',',keys %allow));
                   1244:     unless ($env{'form.makeobsolete'}) {
                   1245:        $intr_scrout.=
1.167     albertel 1246: 	&textfield('Title','title',$metadatafields{'title'}).
                   1247: 	&textfield('Author(s)','author',$metadatafields{'author'}).
                   1248: 	&textfield('Subject','subject',$metadatafields{'subject'});
1.194     www      1249:  # --------------------------------------------------- Scan content for keywords
1.7       www      1250: 
1.238     bisitz   1251:     my $keywords_help = &Apache::loncommon::help_open_topic("Publishing_Keywords");
1.167     albertel 1252:     my $keywordout=<<"END";
1.77      matthew  1253: <script>
1.116     albertel 1254: function checkAll(field) {
1.77      matthew  1255:     for (i = 0; i < field.length; i++)
                   1256:         field[i].checked = true ;
                   1257: }
                   1258: 
1.116     albertel 1259: function uncheckAll(field) {
1.77      matthew  1260:     for (i = 0; i < field.length; i++)
                   1261:         field[i].checked = false ;
                   1262: }
                   1263: </script>
1.117     albertel 1264: END
1.238     bisitz   1265:     $keywordout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Keywords'))
                   1266:                 .$keywords_help
                   1267:                 .'<input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.pubform.keywords)" />'
                   1268:                 .'<input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.pubform.keywords)" />'
                   1269:                 .'</p><br />'
1.247     raeburn  1270:                 .&Apache::loncommon::start_data_table();
                   1271:     my $cols_per_row = 10;
1.167     albertel 1272:     my $colcount=0;
1.247     raeburn  1273:     my $wordcount=0;
                   1274:     my $numkeywords = scalar(keys(%keywords));
1.116     albertel 1275: 
1.247     raeburn  1276:     foreach my $word (sort(keys(%keywords))) {
                   1277:         if ($colcount == 0) {
                   1278:             $keywordout .= &Apache::loncommon::start_data_table_row();
                   1279:         }
                   1280:         $colcount++;
                   1281:         $wordcount++;
                   1282:         if (($wordcount == $numkeywords) && ($colcount < $cols_per_row)) {
                   1283:             my $colspan = 1+$cols_per_row-$colcount;
                   1284:             $keywordout .= '<td colspan="'.$colspan.'">';
                   1285:         } else {
                   1286:             $keywordout .= '<td>';
                   1287:         }
                   1288:         $keywordout.='<label><input type="checkbox" name="keywords" value="'.$word.'"';
                   1289:         if ($metadatafields{'keywords'}) {
                   1290:             if ($metadatafields{'keywords'}=~/\Q$word\E/) {
1.253     bisitz   1291:                 $keywordout.=' checked="checked"';
1.247     raeburn  1292:                 $env{'form.keywords'}.=$word.',';
                   1293:             }
                   1294:         } elsif (&Apache::loncommon::keyword($word)) {
1.253     bisitz   1295:             $keywordout.=' checked="checked"';
1.247     raeburn  1296:             $env{'form.keywords'}.=$word.',';
                   1297:         }
                   1298:         $keywordout.=' />'.$word.'</label></td>';
                   1299:         if ($colcount == $cols_per_row) {
                   1300:             $keywordout.=&Apache::loncommon::end_data_table_row();
                   1301:             $colcount=0;
1.243     bisitz   1302:         }
                   1303:     }
1.247     raeburn  1304:     if ($colcount > 0) {
                   1305:         $keywordout .= &Apache::loncommon::end_data_table_row();
                   1306:     }
1.243     bisitz   1307: 
1.192     albertel 1308:     $env{'form.keywords'}=~s/\,$//;
1.116     albertel 1309: 
1.241     raeburn  1310:     $keywordout.=&Apache::loncommon::end_data_table_row()
                   1311:                  .&Apache::loncommon::end_data_table()
1.238     bisitz   1312:                  .&Apache::lonhtmlcommon::row_closure();
1.51      www      1313: 
1.167     albertel 1314:     $intr_scrout.=$keywordout;
1.9       www      1315: 
1.167     albertel 1316:     $intr_scrout.=&textfield('Additional Keywords','addkey','');
1.12      www      1317: 
1.167     albertel 1318:     $intr_scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
1.9       www      1319: 
1.238     bisitz   1320:     $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Abstract'))
                   1321:                  .'<textarea cols="80" rows="5" name="abstract">'
                   1322:                  .$metadatafields{'abstract'}
                   1323:                  .'</textarea>'
                   1324:                  .&Apache::lonhtmlcommon::row_closure();
1.9       www      1325: 
1.167     albertel 1326:     $source=~/\.(\w+)$/;
1.150     www      1327: 
1.238     bisitz   1328:     $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Grade Levels'))
                   1329:                  .&mt('Lowest Grade Level:').'&nbsp;'
                   1330:                  .&select_level_form($metadatafields{'lowestgradelevel'},'lowestgradelevel')
                   1331: #                .&Apache::lonhtmlcommon::row_closure();
                   1332: #   $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Highest Grade Level'))
                   1333:                  .' '.&mt('Highest Grade Level:').'&nbsp;'
                   1334:                  .&select_level_form($metadatafields{'highestgradelevel'},'highestgradelevel')
                   1335:                  .&Apache::lonhtmlcommon::row_closure();
1.150     www      1336: 
1.238     bisitz   1337:     $intr_scrout.=&textfield('Standards','standards',$metadatafields{'standards'});
1.11      www      1338: 
1.167     albertel 1339:     $intr_scrout.=&hiddenfield('mime',$1);
1.11      www      1340: 
1.167     albertel 1341:     my $defaultlanguage=$metadatafields{'language'};
                   1342:     $defaultlanguage =~ s/\s*notset\s*//g;
                   1343:     $defaultlanguage =~ s/^,\s*//g;
                   1344:     $defaultlanguage =~ s/,\s*$//g;
1.123     albertel 1345: 
1.167     albertel 1346:     $intr_scrout.=&selectbox('Language','language',
                   1347: 			     $defaultlanguage,
                   1348: 			     \&Apache::loncommon::languagedescription,
                   1349: 			     (&Apache::loncommon::languageids),
                   1350: 			     );
1.11      www      1351: 
1.167     albertel 1352:     unless ($metadatafields{'creationdate'}) {
                   1353: 	$metadatafields{'creationdate'}=time;
                   1354:     }
                   1355:     $intr_scrout.=&hiddenfield('creationdate',
                   1356: 			       &Apache::lonmysql::unsqltime($metadatafields{'creationdate'}));
1.116     albertel 1357: 
1.167     albertel 1358:     $intr_scrout.=&hiddenfield('lastrevisiondate',time);
1.11      www      1359: 
1.240     raeburn  1360:     my $pubowner_last;
                   1361:     if ($style eq 'prv') {
                   1362:         $pubowner_last = 1;
                   1363:     }
1.167     albertel 1364:     $intr_scrout.=&textfield('Publisher/Owner','owner',
1.240     raeburn  1365: 			     $metadatafields{'owner'},$pubowner_last);
1.84      bowersj2 1366: 
1.173     www      1367: # ---------------------------------------------- Retrofix for unused copyright
                   1368:     if ($metadatafields{'copyright'} eq 'free') {
                   1369: 	$metadatafields{'copyright'}='default';
                   1370: 	$metadatafields{'sourceavail'}='open';
                   1371:     }
1.229     www      1372:     if ($metadatafields{'copyright'} eq 'priv') {
                   1373:         $metadatafields{'copyright'}='domain';
                   1374:     }
1.174     www      1375: # ------------------------------------------------ Dial in reasonable defaults
1.167     albertel 1376:     my $defaultoption=$metadatafields{'copyright'};
                   1377:     unless ($defaultoption) { $defaultoption='default'; }
1.174     www      1378:     my $defaultsourceoption=$metadatafields{'sourceavail'};
                   1379:     unless ($defaultsourceoption) { $defaultsourceoption='closed'; }
1.167     albertel 1380:     unless ($style eq 'prv') {
1.174     www      1381: # -------------------------------------------------- Correct copyright for rat.
1.167     albertel 1382: 	if ($style eq 'rat') {
1.174     www      1383: # -------------------------------------- Retrofix for non-applicable copyright
1.167     albertel 1384: 	    if ($metadatafields{'copyright'} eq 'public') { 
                   1385: 		delete $metadatafields{'copyright'};
                   1386: 		$defaultoption='default';
                   1387: 	    }
                   1388: 	    $intr_scrout.=&selectbox('Copyright/Distribution','copyright',
                   1389: 				     $defaultoption,
                   1390: 				     \&Apache::loncommon::copyrightdescription,
1.229     www      1391: 				    (grep !/^(public|priv)$/,(&Apache::loncommon::copyrightids)));
1.116     albertel 1392: 	} else {
1.174     www      1393: 	    $intr_scrout.=&selectbox('Copyright/Distribution','copyright',
                   1394: 				     $defaultoption,
                   1395: 				     \&Apache::loncommon::copyrightdescription,
1.229     www      1396: 				     (grep !/^priv$/,(&Apache::loncommon::copyrightids)));
1.65      harris41 1397: 	}
1.174     www      1398: 	my $copyright_help =
1.238     bisitz   1399: 	    &Apache::loncommon::help_open_topic('Publishing_Copyright');
                   1400:         my $replace=&mt('Copyright/Distribution:');
                   1401: 	$intr_scrout =~ s/$replace/$replace.' '.$copyright_help/ge;
                   1402: 
                   1403: 	$intr_scrout.=&text_with_browse_field('Custom Distribution File','customdistributionfile',$metadatafields{'customdistributionfile'},'rights');
1.174     www      1404: 	$intr_scrout.=&selectbox('Source Distribution','sourceavail',
                   1405: 				 $defaultsourceoption,
                   1406: 				 \&Apache::loncommon::source_copyrightdescription,
                   1407: 				 (&Apache::loncommon::source_copyrightids));
1.198     www      1408: #	$intr_scrout.=&text_with_browse_field('Source Custom Distribution File','sourcerights',$metadatafields{'sourcerights'},'rights');
1.174     www      1409: 	my $uctitle=&mt('Obsolete');
1.257     bisitz   1410:         my $obsolete_checked=($metadatafields{'obsolete'})?' checked="checked"':'';
1.238     bisitz   1411:         $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title($uctitle)
1.256     bisitz   1412:                      .'<input type="checkbox" name="obsolete"'.$obsolete_checked.' />'
1.238     bisitz   1413:                      .&Apache::lonhtmlcommon::row_closure(1);
                   1414:         $intr_scrout.=&text_with_browse_field('Suggested Replacement for Obsolete File',
1.180     albertel 1415: 				    'obsoletereplacement',
1.240     raeburn  1416: 				    $metadatafields{'obsoletereplacement'},'',1);
1.174     www      1417:     } else {
                   1418: 	$intr_scrout.=&hiddenfield('copyright','private');
                   1419:     }
1.194     www      1420:    } else {
                   1421:        $intr_scrout.=
                   1422: 	&hiddenfield('title',$metadatafields{'title'}).
                   1423: 	&hiddenfield('author',$metadatafields{'author'}).
                   1424: 	&hiddenfield('subject',$metadatafields{'subject'}).
                   1425: 	&hiddenfield('keywords',$metadatafields{'keywords'}).
                   1426: 	&hiddenfield('abstract',$metadatafields{'abstract'}).
                   1427: 	&hiddenfield('notes',$metadatafields{'notes'}).
                   1428: 	&hiddenfield('mime',$metadatafields{'mime'}).
                   1429: 	&hiddenfield('creationdate',$metadatafields{'creationdate'}).
                   1430: 	&hiddenfield('lastrevisiondate',time).
                   1431: 	&hiddenfield('owner',$metadatafields{'owner'}).
                   1432: 	&hiddenfield('lowestgradelevel',$metadatafields{'lowestgradelevel'}).
                   1433: 	&hiddenfield('standards',$metadatafields{'standards'}).
                   1434: 	&hiddenfield('highestgradelevel',$metadatafields{'highestgradelevel'}).
                   1435: 	&hiddenfield('language',$metadatafields{'language'}).
                   1436: 	&hiddenfield('copyright',$metadatafields{'copyright'}).
                   1437: 	&hiddenfield('sourceavail',$metadatafields{'sourceavail'}).
                   1438: 	&hiddenfield('customdistributionfile',$metadatafields{'customdistributionfile'}).
1.195     www      1439: 	&hiddenfield('obsolete',1).
1.194     www      1440: 	&text_with_browse_field('Suggested Replacement for Obsolete File',
                   1441: 				    'obsoletereplacement',
1.240     raeburn  1442: 				    $metadatafields{'obsoletereplacement'},'',1);
1.194     www      1443:    }
1.167     albertel 1444:     if (!$batch) {
1.238     bisitz   1445: 	$scrout.=$intr_scrout
1.239     bisitz   1446:             .&Apache::lonhtmlcommon::end_pick_box()
                   1447:             .'<p><input type="submit" value="'
1.238     bisitz   1448: 	    .&mt($env{'form.makeobsolete'}?'Make Obsolete':'Finalize Publication')
1.239     bisitz   1449:             .'" /></p>'
                   1450:             .'</form>';
1.97      www      1451:     }
1.167     albertel 1452:     return($scrout,0);
1.2       www      1453: }
1.1       www      1454: 
1.90      matthew  1455: #########################################
                   1456: #########################################
                   1457: 
                   1458: =pod 
                   1459: 
1.94      harris41 1460: =item B<phasetwo>
1.90      matthew  1461: 
                   1462: Render second interface showing status of publication steps.
                   1463: This is publication step two.
                   1464: 
1.94      harris41 1465: Parameters:
                   1466: 
                   1467: =over 4
                   1468: 
                   1469: =item I<$source>
                   1470: 
                   1471: =item I<$target>
                   1472: 
                   1473: =item I<$style>
                   1474: 
                   1475: =item I<$distarget>
                   1476: 
                   1477: =back
                   1478: 
                   1479: Returns:
                   1480: 
                   1481: =over 4
                   1482: 
1.197     www      1483: =item integer
1.94      harris41 1484: 
1.197     www      1485: 0: fail
                   1486: 1: success
1.94      harris41 1487: 
1.90      matthew  1488: =cut
1.12      www      1489: 
1.100     matthew  1490: #'stupid emacs
1.90      matthew  1491: #########################################
                   1492: #########################################
1.11      www      1493: sub phasetwo {
                   1494: 
1.100     matthew  1495:     my ($r,$source,$target,$style,$distarget,$batch)=@_;
1.102     www      1496:     $source=~s/\/+/\//g;
                   1497:     $target=~s/\/+/\//g;
1.196     www      1498: #
                   1499: # Unless trying to get rid of something, check name validity
                   1500: #
                   1501:     unless ($env{'form.obsolete'}) {
                   1502: 	if ($target=~/(\_\_\_|\&\&\&|\:\:\:)/) {
1.226     albertel 1503: 	    $r->print('<span class="LC_error">'.
                   1504: 		      &mt('Unsupported character combination [_1] in filename, FAIL.',"<tt>'.$1.'</tt>").
                   1505: 		      '</span>');
1.196     www      1506: 	    return 0;
                   1507: 	}
                   1508: 	unless ($target=~/\.(\w+)$/) {
1.226     albertel 1509: 	    $r->print('<span class="LC_error">'.&mt('No valid extension found in filename, FAIL').'</span>');
1.196     www      1510: 	    return 0;
                   1511: 	}
                   1512: 	if ($target=~/\.(\d+)\.(\w+)$/) {
1.254     bisitz   1513: 	    $r->print('<span class="LC_error">'.&mt('Filename of resource contains internal version number. Cannot publish such resources, FAIL').'</span>');
1.196     www      1514: 	    return 0;
                   1515: 	}
                   1516:     }
1.109     www      1517: 
1.196     www      1518: #
                   1519: # End name check
                   1520: #
1.102     www      1521:     $distarget=~s/\/+/\//g;
1.11      www      1522:     my $logfile;
                   1523:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1.110     www      1524: 	$r->print(
1.226     albertel 1525:         '<span class="LC_error">'.
                   1526: 		&mt('No write permission to user directory, FAIL').'</span>');
1.110     www      1527:         return 0;
1.11      www      1528:     }
1.227     albertel 1529:     
                   1530:     if ($source =~ /\.rights$/) {
                   1531: 	$r->print('<p><span class="LC_warning">'.&mt('Warning: It can take up to 1 hour for rights changes to fully propagate.').'</span></p>');
                   1532:     }
                   1533: 
1.11      www      1534:     print $logfile 
1.211     albertel 1535:         "\n================= Publish ".localtime()." Phase Two  ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
1.100     matthew  1536:     
                   1537:     %metadatafields=();
                   1538:     %metadatakeys=();
1.167     albertel 1539: 
1.209     www      1540:     &metaeval(&unescape($env{'form.allmeta'}));
1.100     matthew  1541:     
1.192     albertel 1542:     $metadatafields{'title'}=$env{'form.title'};
                   1543:     $metadatafields{'author'}=$env{'form.author'};
                   1544:     $metadatafields{'subject'}=$env{'form.subject'};
                   1545:     $metadatafields{'notes'}=$env{'form.notes'};
                   1546:     $metadatafields{'abstract'}=$env{'form.abstract'};
                   1547:     $metadatafields{'mime'}=$env{'form.mime'};
                   1548:     $metadatafields{'language'}=$env{'form.language'};
                   1549:     $metadatafields{'creationdate'}=$env{'form.creationdate'};
                   1550:     $metadatafields{'lastrevisiondate'}=$env{'form.lastrevisiondate'};
                   1551:     $metadatafields{'owner'}=$env{'form.owner'};
                   1552:     $metadatafields{'copyright'}=$env{'form.copyright'};
                   1553:     $metadatafields{'standards'}=$env{'form.standards'};
                   1554:     $metadatafields{'lowestgradelevel'}=$env{'form.lowestgradelevel'};
                   1555:     $metadatafields{'highestgradelevel'}=$env{'form.highestgradelevel'};
1.115     www      1556:     $metadatafields{'customdistributionfile'}=
1.192     albertel 1557:                                  $env{'form.customdistributionfile'};
                   1558:     $metadatafields{'sourceavail'}=$env{'form.sourceavail'};
                   1559:     $metadatafields{'obsolete'}=$env{'form.obsolete'};
1.138     www      1560:     $metadatafields{'obsoletereplacement'}=
1.192     albertel 1561: 	                        $env{'form.obsoletereplacement'};
                   1562:     $metadatafields{'dependencies'}=$env{'form.dependencies'};
1.211     albertel 1563:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
1.192     albertel 1564: 	                                 $env{'user.domain'};
1.211     albertel 1565:     $metadatafields{'authorspace'}=$cuname.':'.$cudom;
1.214     albertel 1566:     $metadatafields{'domain'}=$cudom;
1.100     matthew  1567:     
1.192     albertel 1568:     my $allkeywords=$env{'form.addkey'};
                   1569:     if (exists($env{'form.keywords'})) {
                   1570:         if (ref($env{'form.keywords'})) {
                   1571:             $allkeywords .= ','.join(',',@{$env{'form.keywords'}});
1.100     matthew  1572:         } else {
1.192     albertel 1573:             $allkeywords .= ','.$env{'form.keywords'};
1.100     matthew  1574:         }
                   1575:     }
1.168     www      1576:     $allkeywords=~s/[\"\']//g;
1.170     www      1577:     $allkeywords=~s/\s*[\;\,]\s*/\,/g;
1.168     www      1578:     $allkeywords=~s/\s+/ /g;
                   1579:     $allkeywords=~s/^[ \,]//;
                   1580:     $allkeywords=~s/[ \,]$//;
1.100     matthew  1581:     $metadatafields{'keywords'}=$allkeywords;
                   1582:     
1.149     www      1583: # check if custom distribution file is specified
                   1584:     if ($metadatafields{'copyright'} eq 'custom') {
                   1585: 	my $file=$metadatafields{'customdistributionfile'};
                   1586: 	unless ($file=~/\.rights$/) {
1.197     www      1587:             $r->print(
1.226     albertel 1588:                 '<span class="LC_error">'.&mt('No valid custom distribution rights file specified, FAIL').
                   1589: 		'</span>');
1.197     www      1590: 	    return 0;
1.149     www      1591:         }
                   1592:     }
1.100     matthew  1593:     {
                   1594:         print $logfile "\nWrite metadata file for ".$source;
                   1595:         my $mfh;
                   1596:         unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
1.197     www      1597:             $r->print( 
1.226     albertel 1598:                 '<span class="LC_error">'.&mt('Could not write metadata, FAIL').
                   1599: 		'</span>');
1.197     www      1600: 	    return 0;
1.100     matthew  1601:         }
                   1602:         foreach (sort keys %metadatafields) {
                   1603:             unless ($_=~/\./) {
                   1604:                 my $unikey=$_;
                   1605:                 $unikey=~/^([A-Za-z]+)/;
                   1606:                 my $tag=$1;
                   1607:                 $tag=~tr/A-Z/a-z/;
                   1608:                 print $mfh "\n\<$tag";
                   1609:                 foreach (split(/\,/,$metadatakeys{$unikey})) {
                   1610:                     my $value=$metadatafields{$unikey.'.'.$_};
                   1611:                     $value=~s/\"/\'\'/g;
                   1612:                     print $mfh ' '.$_.'="'.$value.'"';
                   1613:                 }
                   1614:                 print $mfh '>'.
1.165     albertel 1615:                     &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
1.100     matthew  1616:                         .'</'.$tag.'>';
                   1617:             }
                   1618:         }
1.136     www      1619:         $r->print('<p>'.&mt('Wrote Metadata').'</p>');
1.100     matthew  1620:         print $logfile "\nWrote metadata";
                   1621:     }
                   1622:     
                   1623: # -------------------------------- Synchronize entry with SQL metadata database
1.12      www      1624: 
1.89      matthew  1625:     $metadatafields{'url'} = $distarget;
                   1626:     $metadatafields{'version'} = 'current';
1.152     www      1627: 
                   1628:     my ($error,$success) = &store_metadata(%metadatafields);
                   1629:     if ($success) {
                   1630: 	$r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
                   1631: 	print $logfile "\nSynchronized SQL metadata database";
1.89      matthew  1632:     } else {
1.152     www      1633: 	$r->print($error);
                   1634: 	print $logfile "\n".$error;
1.24      harris41 1635:     }
1.159     www      1636: # --------------------------------------------- Delete author resource messages
                   1637:     my $delresult=&Apache::lonmsg::del_url_author_res_msg($target); 
                   1638:     $r->print('<p>'.&mt('Removing error messages:').' '.$delresult.'</p>');
                   1639:     print $logfile "\nRemoving error messages: $delresult";
1.12      www      1640: # ----------------------------------------------------------- Copy old versions
                   1641:    
1.100     matthew  1642:     if (-e $target) {
                   1643:         my $filename;
                   1644:         my $maxversion=0;
                   1645:         $target=~/(.*)\/([^\/]+)\.(\w+)$/;
                   1646:         my $srcf=$2;
                   1647:         my $srct=$3;
                   1648:         my $srcd=$1;
1.261     raeburn  1649:         my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   1650:         unless ($srcd=~/^\Q$docroot\E\/res/) {
1.100     matthew  1651:             print $logfile "\nPANIC: Target dir is ".$srcd;
1.197     www      1652:             $r->print(
1.239     bisitz   1653: 	 "<span class=\"LC_error\">".&mt('Invalid target directory, FAIL')."</span>");
1.197     www      1654: 	    return 0;
1.100     matthew  1655:         }
                   1656:         opendir(DIR,$srcd);
                   1657:         while ($filename=readdir(DIR)) {
                   1658:             if (-l $srcd.'/'.$filename) {
                   1659:                 unlink($srcd.'/'.$filename);
                   1660:                 unlink($srcd.'/'.$filename.'.meta');
                   1661:             } else {
1.252     raeburn  1662:                 if ($filename=~/^\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
1.100     matthew  1663:                     $maxversion=($1>$maxversion)?$1:$maxversion;
                   1664:                 }
                   1665:             }
                   1666:         }
                   1667:         closedir(DIR);
                   1668:         $maxversion++;
1.254     bisitz   1669:         $r->print('<p>'.&mt('Creating old version [_1]',$maxversion).'</p>');
1.125     www      1670:         print $logfile "\nCreating old version ".$maxversion."\n";
1.100     matthew  1671:         
                   1672:         my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
                   1673:         
1.13      www      1674:         if (copy($target,$copyfile)) {
1.12      www      1675: 	    print $logfile "Copied old target to ".$copyfile."\n";
1.265     www      1676:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied old target file')));
1.12      www      1677:         } else {
1.13      www      1678: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
1.265     www      1679:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Failed to copy old target').", $!",1));
1.197     www      1680: 	    return 0;
1.12      www      1681:         }
1.100     matthew  1682:         
1.12      www      1683: # --------------------------------------------------------------- Copy Metadata
                   1684: 
                   1685: 	$copyfile=$copyfile.'.meta';
1.100     matthew  1686:         
1.13      www      1687:         if (copy($target.'.meta',$copyfile)) {
1.14      www      1688: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
1.265     www      1689:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied old metadata')));
1.12      www      1690:         } else {
1.13      www      1691: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1.14      www      1692:             if (-e $target.'.meta') {
1.265     www      1693:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
                   1694:                            &mt('Failed to write old metadata copy').", $!",1));
1.197     www      1695: 		return 0;
1.14      www      1696: 	    }
1.12      www      1697:         }
1.100     matthew  1698:         
                   1699:         
                   1700:     } else {
1.138     www      1701:         $r->print('<p>'.&mt('Initial version').'</p>');
1.100     matthew  1702:         print $logfile "\nInitial version";
                   1703:     }
1.12      www      1704: 
                   1705: # ---------------------------------------------------------------- Write Source
1.100     matthew  1706:     my $copyfile=$target;
                   1707:     
                   1708:     my @parts=split(/\//,$copyfile);
                   1709:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1710:     
                   1711:     my $count;
                   1712:     for ($count=5;$count<$#parts;$count++) {
                   1713:         $path.="/$parts[$count]";
                   1714:         if ((-e $path)!=1) {
                   1715:             print $logfile "\nCreating directory ".$path;
                   1716:             mkdir($path,0777);
1.255     bisitz   1717:             $r->print('<p>'
                   1718:                      .&mt('Created directory [_1]'
                   1719:                          ,'<span class="LC_filename">'.$parts[$count].'</span>')
                   1720:                      .'</p>'
                   1721:             );
1.12      www      1722:         }
1.100     matthew  1723:     }
                   1724:     
                   1725:     if (copy($source,$copyfile)) {
                   1726:         print $logfile "\nCopied original source to ".$copyfile."\n";
1.265     www      1727:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied source file')));
1.100     matthew  1728:     } else {
                   1729:         print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
1.265     www      1730:         $r->print(&Apache::lonhtmlcommon::confirm_success(
                   1731: 	    &mt('Failed to copy source').", $!",1));
1.197     www      1732: 	return 0;
1.100     matthew  1733:     }
                   1734:     
1.265     www      1735: # ---------------------------------------------- Delete local tmp-preview files
                   1736:     unlink($copyfile.'.tmp');
1.12      www      1737: # --------------------------------------------------------------- Copy Metadata
                   1738: 
1.100     matthew  1739:     $copyfile=$copyfile.'.meta';
                   1740:     
                   1741:     if (copy($source.'.meta',$copyfile)) {
                   1742:         print $logfile "\nCopied original metadata to ".$copyfile."\n";
1.265     www      1743:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied metadata')));
1.100     matthew  1744:     } else {
                   1745:         print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
1.265     www      1746:         $r->print(&Apache::lonhtmlcommon::confirm_success(
                   1747:                   &mt('Failed to write metadata copy').", $!",1));
1.197     www      1748: 	return 0;
1.100     matthew  1749:     }
                   1750:     $r->rflush;
1.12      www      1751: 
1.181     www      1752: # ------------------------------------------------------------- Trigger updates
1.183     www      1753:     push(@{$modified_urls},[$target,$source]);
1.182     www      1754:     unless ($registered_cleanup) {
1.263     raeburn  1755:         my $handlers = $r->get_handlers('PerlCleanupHandler');
                   1756:         $r->set_handlers('PerlCleanupHandler' => [\&notify,@{$handlers}]);
1.182     www      1757: 	$registered_cleanup=1;
                   1758:     }
1.199     www      1759: 
                   1760: # ---------------------------------------------------------- Clear local caches
                   1761:     my $thisdistarget=$target;
                   1762:     $thisdistarget=~s/^\Q$docroot\E//;
                   1763:     &Apache::lonnet::devalidate_cache_new('resversion',$target);
                   1764:     &Apache::lonnet::devalidate_cache_new('meta',
                   1765: 			 &Apache::lonnet::declutter($thisdistarget));
                   1766: 
1.255     bisitz   1767: # ------------------------------------------------------------- Everything done
                   1768:     $logfile->close();
                   1769:     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
                   1770: 
1.12      www      1771: # ------------------------------------------------ Provide link to new resource
1.100     matthew  1772:     unless ($batch) {
                   1773:         
1.271     www      1774:         my $thissrc=&Apache::loncfile::url($source);
1.100     matthew  1775:         my $thissrcdir=$thissrc;
                   1776:         $thissrcdir=~s/\/[^\/]+$/\//;
                   1777:         
1.264     raeburn  1778:         $r->print(&Apache::loncommon::head_subbox(
                   1779:             &Apache::lonhtmlcommon::start_funclist().
                   1780:             &Apache::lonhtmlcommon::add_item_funclist(
                   1781:                 '<a href="'.$thisdistarget.'">'.
                   1782:                 &mt('View Published Version').
                   1783:                 '</a>').
                   1784:             &Apache::lonhtmlcommon::add_item_funclist(
                   1785:                 '<a href="'.$thissrc.'">'.
                   1786:                 &mt('Back to Source').
                   1787:                 '</a>').
1.262     bisitz   1788:             &Apache::lonhtmlcommon::add_item_funclist(
1.264     raeburn  1789:                 '<a href="'.$thissrcdir.'">'.
                   1790:                 &mt('Back to Source Directory').
                   1791:                 '</a>').
                   1792:             &Apache::lonhtmlcommon::end_funclist())
1.262     bisitz   1793:         );
1.100     matthew  1794:     }
1.197     www      1795:     return 1;
1.11      www      1796: }
                   1797: 
1.181     www      1798: # =============================================================== Notifications
                   1799: sub notify {  
                   1800: # --------------------------------------------------- Send update notifications
1.183     www      1801:     foreach my $targetsource (@{$modified_urls}){
1.182     www      1802: 	my ($target,$source)=@{$targetsource};
                   1803: 	my $logfile=Apache::File->new('>>'.$source.'.log');
                   1804: 	print $logfile "\nCleanup phase: Notifications\n";
                   1805: 	my @subscribed=&get_subscribed_hosts($target);
                   1806: 	foreach my $subhost (@subscribed) {
                   1807: 	    print $logfile "\nNotifying host ".$subhost.':';
                   1808: 	    my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
                   1809: 	    print $logfile $reply;
                   1810: 	}
1.181     www      1811: # ---------------------------------------- Send update notifications, meta only
1.182     www      1812: 	my @subscribedmeta=&get_subscribed_hosts("$target.meta");
                   1813: 	foreach my $subhost (@subscribedmeta) {
                   1814: 	    print $logfile "\nNotifying host for metadata only ".$subhost.':';
                   1815: 	    my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
                   1816: 						$subhost);
                   1817: 	    print $logfile $reply;
                   1818: 	} 
1.181     www      1819: # --------------------------------------------------- Notify subscribed courses
1.182     www      1820: 	my %courses=&coursedependencies($target);
                   1821: 	my $now=time;
                   1822: 	foreach (keys %courses) {
                   1823: 	    print $logfile "\nNotifying course ".$_.':';
                   1824: 	    my ($cdom,$cname)=split(/\_/,$_);
                   1825: 	    my $reply=&Apache::lonnet::cput
                   1826: 		('versionupdate',{$target => $now},$cdom,$cname);
                   1827: 	    print $logfile $reply;
                   1828: 	}
                   1829: 	print $logfile "\n============ Done ============\n";
                   1830: 	$logfile->close();
1.181     www      1831:     }
1.233     www      1832:     if ($lock) { &Apache::lonnet::remove_lock($lock); }
1.182     www      1833:     return OK;
1.181     www      1834: }
                   1835: 
1.95      www      1836: #########################################
                   1837: 
                   1838: sub batchpublish {
1.97      www      1839:     my ($r,$srcfile,$targetfile)=@_;
1.192     albertel 1840:     #publication pollutes %env with form.* values
                   1841:     my %oldenv=%env;
1.102     www      1842:     $srcfile=~s/\/+/\//g;
                   1843:     $targetfile=~s/\/+/\//g;
1.95      www      1844:     $srcfile=~s/\/+/\//g;
1.96      www      1845: 
1.97      www      1846:     my $docroot=$r->dir_config('lonDocRoot');
                   1847:     my $thisdistarget=$targetfile;
1.122     albertel 1848:     $thisdistarget=~s/^\Q$docroot\E//;
1.97      www      1849: 
1.96      www      1850: 
1.139     albertel 1851:     %metadatafields=();
                   1852:     %metadatakeys=();
                   1853:     $srcfile=~/\.(\w+)$/;
                   1854:     my $thistype=$1;
1.97      www      1855: 
                   1856: 
1.139     albertel 1857:     my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1.96      www      1858:      
1.254     bisitz   1859:     $r->print('<h2>'
1.271     www      1860:              .&mt('Publishing [_1]',&Apache::loncfile::display($srcfile))
1.254     bisitz   1861:              .'</h2>'
                   1862:     );
1.97      www      1863: 
                   1864: # phase one takes
                   1865: #  my ($source,$target,$style,$batch)=@_;
1.113     albertel 1866:     my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
                   1867:     $r->print('<p>'.$outstring.'</p>');
1.96      www      1868: # phase two takes
                   1869: # my ($source,$target,$style,$distarget,batch)=@_;
1.192     albertel 1870: # $env{'form.allmeta'},$env{'form.title'},$env{'form.author'},...
1.113     albertel 1871:     if (!$error) {
                   1872: 	$r->print('<p>');
                   1873: 	&phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
                   1874: 	$r->print('</p>');
                   1875:     }
1.192     albertel 1876:     %env=%oldenv;
1.97      www      1877:     return '';
1.95      www      1878: }
1.1       www      1879: 
1.90      matthew  1880: #########################################
1.95      www      1881: 
                   1882: sub publishdirectory {
                   1883:     my ($r,$fn,$thisdisfn)=@_;
1.102     www      1884:     $fn=~s/\/+/\//g;
                   1885:     $thisdisfn=~s/\/+/\//g;
1.273     www      1886:     my $thisdisresdir=$thisdisfn;
                   1887:     $thisdisresdir=~s/^\/priv\//\/res\//;
1.276     raeburn  1888:     my $resdir = $r->dir_config('lonDocRoot').$thisdisresdir;
1.258     bisitz   1889:     $r->print(&Apache::lonhtmlcommon::start_pick_box()
                   1890:              .&Apache::lonhtmlcommon::row_title(&mt('Directory'))
                   1891:             .'<span class="LC_filename">'.$thisdisfn.'</span>'
                   1892:             .&Apache::lonhtmlcommon::row_closure()
                   1893:             .&Apache::lonhtmlcommon::row_title(&mt('Target'))
1.273     www      1894:             .'<span class="LC_filename">'.$thisdisresdir.'</span>'
1.258     bisitz   1895:     );
1.139     albertel 1896: 
                   1897:     my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
1.193     www      1898:     unless ($env{'form.phase'} eq 'two') {
                   1899: # ask user what they want
1.258     bisitz   1900:         $r->print(&Apache::lonhtmlcommon::row_closure()
                   1901:                  .&Apache::lonhtmlcommon::row_title(&mt('Options'))
                   1902:         );
1.193     www      1903:         $r->print('<form name="pubdirpref" method="post">'.
                   1904: 		  &hiddenfield('phase','two').
                   1905: 		  &hiddenfield('filename',$env{'form.filename'}).
                   1906: 		  &checkbox('pubrec','include subdirectories').
1.194     www      1907: 		  &checkbox('forcerepub','force republication of previously published files').
1.206     albertel 1908:                   &checkbox('obsolete','make file(s) obsolete').
1.250     schafran 1909: 		  &checkbox('forceoverride','force directory level metadata over existing').
1.195     www      1910: 		  '<br /><input type="submit" value="'.&mt('Publish Directory').'" /></form>');
1.258     bisitz   1911:         $r->print(&Apache::lonhtmlcommon::row_closure(1)
                   1912:                  .&Apache::lonhtmlcommon::end_pick_box()
                   1913:         );
1.233     www      1914:         $lock=0;
1.193     www      1915:     } else {
1.258     bisitz   1916:         $r->print(&Apache::lonhtmlcommon::row_closure(1)
                   1917:                  .&Apache::lonhtmlcommon::end_pick_box()
                   1918:         );
1.234     www      1919:         unless ($lock) { $lock=&Apache::lonnet::set_lock(&mt('Publishing [_1]',$fn)); }
1.193     www      1920: # actually publish things
                   1921: 	opendir(DIR,$fn);
                   1922: 	my @files=sort(readdir(DIR));
                   1923: 	foreach my $filename (@files) {
                   1924: 	    my ($cdev,$cino,$cmode,$cnlink,
                   1925: 		$cuid,$cgid,$crdev,$csize,
                   1926: 		$catime,$cmtime,$cctime,
                   1927: 		$cblksize,$cblocks)=stat($fn.'/'.$filename);
                   1928: 	    
                   1929: 	    my $extension='';
                   1930: 	    if ($filename=~/\.(\w+)$/) { $extension=$1; }
                   1931: 	    if ($cmode&$dirptr) {
                   1932: 		if (($filename!~/^\./) && ($env{'form.pubrec'})) {
1.273     www      1933: 		    &publishdirectory($r,$docroot.$fn.'/'.$filename,$thisdisfn.'/'.$filename);
1.193     www      1934: 		}
                   1935: 	    } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
                   1936: 		     ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
1.96      www      1937: # find out publication status and/or exiting metadata
1.193     www      1938: 		my $publishthis=0;
                   1939: 		if (-e $resdir.'/'.$filename) {
                   1940: 		    my ($rdev,$rino,$rmode,$rnlink,
                   1941: 			$ruid,$rgid,$rrdev,$rsize,
                   1942: 			$ratime,$rmtime,$rctime,
                   1943: 			$rblksize,$rblocks)=stat($resdir.'/'.$filename);
                   1944: 		    if (($rmtime<$cmtime) || ($env{'form.forcerepub'})) {
1.96      www      1945: # previously published, modified now
1.193     www      1946: 			$publishthis=1;
                   1947: 		    }
1.212     albertel 1948: 		    my $meta_cmtime = (stat($fn.'/'.$filename.'.meta'))[9];
                   1949: 		    my $meta_rmtime = (stat($resdir.'/'.$filename.'.meta'))[9];
                   1950: 		    if ( $meta_rmtime<$meta_cmtime ) {
                   1951: 			$publishthis=1;
                   1952: 		    }
1.193     www      1953: 		} else {
                   1954: # never published
1.96      www      1955: 		    $publishthis=1;
1.193     www      1956: 		}
1.212     albertel 1957: 		
1.193     www      1958: 		if ($publishthis) {
                   1959: 		    &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
                   1960: 		} else {
                   1961: 		    $r->print('<br />'.&mt('Skipping').' '.$filename.'<br />');
                   1962: 		}
                   1963: 		$r->rflush();
1.139     albertel 1964: 	    }
                   1965: 	}
1.193     www      1966: 	closedir(DIR);
1.139     albertel 1967:     }
1.95      www      1968: }
1.160     www      1969: 
                   1970: #########################################
                   1971: # publish a default.meta file
                   1972: 
                   1973: sub defaultmetapublish {
                   1974:     my ($r,$fn,$cuname,$cudom)=@_;
                   1975:     unless (-e $fn) {
                   1976:        return HTTP_NOT_FOUND;
                   1977:     }
                   1978:     my $target=$fn;
1.270     www      1979:     $target=~s/^\Q$Apache::lonnet::perlvar{'lonDocRoot'}\E\/priv\//\Q$Apache::lonnet::perlvar{'lonDocRoot'}\E\/res\//;
1.160     www      1980: 
                   1981: 
                   1982:     &Apache::loncommon::content_type($r,'text/html');
                   1983:     $r->send_http_header;
                   1984: 
1.251     schafran 1985:     $r->print(&Apache::loncommon::start_page('Metadata Publication'));
1.160     www      1986: 
                   1987: # ---------------------------------------------------------------- Write Source
                   1988:     my $copyfile=$target;
                   1989:     
                   1990:     my @parts=split(/\//,$copyfile);
                   1991:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1992:     
                   1993:     my $count;
                   1994:     for ($count=5;$count<$#parts;$count++) {
                   1995:         $path.="/$parts[$count]";
                   1996:         if ((-e $path)!=1) {
                   1997:             mkdir($path,0777);
1.255     bisitz   1998:             $r->print('<p>'
                   1999:                      .&mt('Created directory [_1]'
                   2000:                          ,'<span class="LC_filename">'.$parts[$count].'</span>')
                   2001:                      .'</p>'
                   2002:             );
1.160     www      2003:         }
                   2004:     }
                   2005:     
                   2006:     if (copy($fn,$copyfile)) {
                   2007:         $r->print('<p>'.&mt('Copied source file').'</p>');
                   2008:     } else {
1.226     albertel 2009:         return "<span class=\"LC_error\">".
                   2010: 	    &mt('Failed to copy source').", $!, ".&mt('FAIL')."</span>";
1.160     www      2011:     }
                   2012: 
                   2013: # --------------------------------------------------- Send update notifications
                   2014: 
                   2015:     my @subscribed=&get_subscribed_hosts($target);
                   2016:     foreach my $subhost (@subscribed) {
                   2017: 	$r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
                   2018: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
                   2019: 	$r->print($reply.'</p><br />');$r->rflush;
                   2020:     }
                   2021: # ------------------------------------------------------------------- Link back
1.270     www      2022:     $r->print("<a href='".&Apache::lonnet::display($fn)."'>".&mt('Back to Metadata').'</a>');
1.208     albertel 2023:     $r->print(&Apache::loncommon::end_page());
1.160     www      2024:     return OK;
                   2025: }
1.90      matthew  2026: #########################################
                   2027: 
                   2028: =pod
                   2029: 
1.94      harris41 2030: =item B<handler>
1.90      matthew  2031: 
                   2032: A basic outline of the handler subroutine follows.
                   2033: 
                   2034: =over 4
                   2035: 
1.94      harris41 2036: =item *
                   2037: 
                   2038: Get query string for limited number of parameters.
                   2039: 
                   2040: =item *
                   2041: 
                   2042: Check filename.
                   2043: 
                   2044: =item *
                   2045: 
                   2046: File is there and owned, init lookup tables.
                   2047: 
                   2048: =item *
1.90      matthew  2049: 
1.94      harris41 2050: Start page output.
1.90      matthew  2051: 
1.94      harris41 2052: =item *
1.90      matthew  2053: 
1.94      harris41 2054: Evaluate individual file, and then output information.
1.90      matthew  2055: 
1.94      harris41 2056: =item *
1.90      matthew  2057: 
1.94      harris41 2058: Publishing from $thisfn to $thistarget with $thisembstyle.
1.90      matthew  2059: 
                   2060: =back
                   2061: 
                   2062: =cut
                   2063: 
                   2064: #########################################
                   2065: #########################################
1.1       www      2066: sub handler {
1.139     albertel 2067:     my $r=shift;
1.2       www      2068: 
1.139     albertel 2069:     if ($r->header_only) {
                   2070: 	&Apache::loncommon::content_type($r,'text/html');
                   2071: 	$r->send_http_header;
                   2072: 	return OK;
                   2073:     }
1.2       www      2074: 
1.43      www      2075: # Get query string for limited number of parameters
                   2076: 
1.80      matthew  2077:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2078:                                             ['filename']);
1.43      www      2079: 
1.183     www      2080: # -------------------------------------- Flag and buffer for registered cleanup
1.182     www      2081:     $registered_cleanup=0;
1.183     www      2082:     @{$modified_urls}=();
1.2       www      2083: # -------------------------------------------------------------- Check filename
                   2084: 
1.209     www      2085:     my $fn=&unescape($env{'form.filename'});
1.268     www      2086:     ($cuname,$cudom)=&Apache::loncacc::constructaccess($fn);
                   2087: # ----------------------------------------------------- Do we have permissions?
                   2088:      unless (($cuname) && ($cudom)) {
                   2089:        $r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
                   2090:                       ' trying to publish file '.$env{'form.filename'}.
                   2091:                       ' - not authorized', 
                   2092:                       $r->filename); 
                   2093:        return HTTP_NOT_ACCEPTABLE;
                   2094:      }
                   2095: # ----------------------------------------------------------------- Get docroot
                   2096:     $docroot=$r->dir_config('lonDocRoot');
1.160     www      2097: 
                   2098: 
                   2099: # special publication: default.meta file
                   2100:     if ($fn=~/\/default.meta$/) {
                   2101: 	return &defaultmetapublish($r,$fn,$cuname,$cudom); 
                   2102:     }
1.159     www      2103:     $fn=~s/\.meta$//;
1.268     www      2104: 
                   2105: # sanity test on the filename 
                   2106:  
1.139     albertel 2107:     unless ($fn) { 
                   2108: 	$r->log_reason($cuname.' at '.$cudom.
                   2109: 		       ' trying to publish empty filename', $r->filename); 
                   2110: 	return HTTP_NOT_FOUND;
                   2111:     } 
                   2112: 
1.268     www      2113:     unless (-e $docroot.$fn) { 
1.139     albertel 2114: 	$r->log_reason($cuname.' at '.$cudom.
                   2115: 		       ' trying to publish non-existing file '.
1.192     albertel 2116: 		       $env{'form.filename'}.' ('.$fn.')', 
1.139     albertel 2117: 		       $r->filename); 
                   2118: 	return HTTP_NOT_FOUND;
                   2119:     } 
1.2       www      2120: 
1.94      harris41 2121: # -------------------------------- File is there and owned, init lookup tables.
1.2       www      2122: 
1.205     albertel 2123:     %addid=();
                   2124:     
                   2125:     {
                   2126: 	my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
                   2127: 	while (<$fh>=~/(\w+)\s+(\w+)/) {
                   2128: 	    $addid{$1}=$2;
1.139     albertel 2129: 	}
1.205     albertel 2130:     }
1.3       www      2131: 
1.205     albertel 2132:     %nokey=();
1.11      www      2133: 
1.205     albertel 2134:     {
                   2135: 	my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
                   2136: 	while (<$fh>) {
                   2137: 	    my $word=$_;
                   2138: 	    chomp($word);
                   2139: 	    $nokey{$word}=1;
1.139     albertel 2140: 	}
                   2141:     }
1.11      www      2142: 
1.94      harris41 2143: # ---------------------------------------------------------- Start page output.
1.2       www      2144: 
1.139     albertel 2145:     &Apache::loncommon::content_type($r,'text/html');
                   2146:     $r->send_http_header;
1.180     albertel 2147:     
1.259     bisitz   2148:     # Breadcrumbs
                   2149:     &Apache::lonhtmlcommon::clear_breadcrumbs();
                   2150:     &Apache::lonhtmlcommon::add_breadcrumb({
                   2151:         'text'  => 'Construction Space',
1.277     raeburn  2152:         'href'  => &Apache::loncommon::authorspace($fn),
1.259     bisitz   2153:     });
                   2154:     &Apache::lonhtmlcommon::add_breadcrumb({
                   2155:         'text'  => 'Resource Publication',
                   2156:         'href'  => '',
                   2157:     });
                   2158: 
1.208     albertel 2159:     my $js='<script type="text/javascript">'.
                   2160: 	&Apache::loncommon::browser_and_searcher_javascript().
                   2161: 	'</script>';
1.259     bisitz   2162:     $r->print(&Apache::loncommon::start_page('Resource Publication',$js)
                   2163:              .&Apache::lonhtmlcommon::breadcrumbs()
                   2164:              .&Apache::loncommon::head_subbox(
1.275     raeburn  2165:                   &Apache::loncommon::CSTR_pageheader($docroot.$fn))
1.259     bisitz   2166:     );
1.101     www      2167: 
1.268     www      2168:     my $thisdisfn=&HTML::Entities::encode($fn,'<>&"');
                   2169:     my $thistarget=$fn;
                   2170:     $thistarget=~s/^\/priv\//\/res\//;
                   2171:     my $thisdistarget=&HTML::Entities::encode($thistarget,'<>&"');
1.95      www      2172: 
1.139     albertel 2173:     if ($fn=~/\/$/) {
1.95      www      2174: # -------------------------------------------------------- This is a directory
1.273     www      2175: 	&publishdirectory($r,$docroot.$fn,$thisdisfn);
1.268     www      2176: 	$r->print('<hr /><a href="'.$thisdisfn.'">'.&mt('Return to Directory').'</a>');
1.139     albertel 2177:     } else {
1.94      harris41 2178: # ---------------------- Evaluate individual file, and then output information.
1.268     www      2179: 	$fn=~/\.(\w+)$/;
1.139     albertel 2180: 	my $thistype=$1;
                   2181: 	my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1.200     raeburn  2182:         if ($thistype eq 'page') {  $thisembstyle = 'rat'; }
1.2       www      2183: 
1.254     bisitz   2184:         $r->print('<h2>'
                   2185:                  .&mt('Publishing [_1]'
                   2186:                      ,'<span class="LC_filename">'.$thisdisfn.'</span>')
                   2187:                  .'</h2>'
                   2188:         );
1.239     bisitz   2189: 
                   2190:         $r->print('<h3>'.&mt('Resource Details').'</h3>');
                   2191: 
                   2192:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
                   2193: 
                   2194:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Type'))
                   2195:                  .&Apache::loncommon::filedescription($thistype)
                   2196:                  .&Apache::lonhtmlcommon::row_closure()
                   2197:                  );
                   2198: 
                   2199:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Link to Resource'))
                   2200:                  .'<tt>'
                   2201:                  );
1.139     albertel 2202: 	$r->print(<<ENDCAPTION);
1.268     www      2203: <a href='javascript:void(window.open("$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
1.129     www      2204: $thisdisfn</a>
                   2205: ENDCAPTION
1.239     bisitz   2206:         $r->print('</tt>'
                   2207:                  .&Apache::lonhtmlcommon::row_closure()
                   2208:                  );
                   2209: 
                   2210:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Target'))
                   2211:                  .'<tt>'.$thisdistarget.'</tt>'
                   2212:                  );
1.192     albertel 2213: 	if (($cuname ne $env{'user.name'})||($cudom ne $env{'user.domain'})) {
1.240     raeburn  2214:             $r->print(&Apache::lonhtmlcommon::row_closure()
                   2215:                      .&Apache::lonhtmlcommon::row_title(&mt('Co-Author'))
1.239     bisitz   2216:                      .'<span class="LC_warning">'
1.258     bisitz   2217: 		     .&Apache::loncommon::plainname($cuname,$cudom) .' ('.$cuname.':'.$cudom.')'
1.239     bisitz   2218:                      .'</span>'
                   2219:                      );
1.139     albertel 2220: 	}
1.26      www      2221: 
1.139     albertel 2222: 	if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
1.240     raeburn  2223:             $r->print(&Apache::lonhtmlcommon::row_closure()
                   2224:                      .&Apache::lonhtmlcommon::row_title(&mt('Diffs')));
1.139     albertel 2225: 	    $r->print(<<ENDDIFF);
1.268     www      2226: <a href='javascript:void(window.open("/adm/diff?filename=$thisdisfn&versiontwo=priv","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
1.129     www      2227: ENDDIFF
1.240     raeburn  2228:             $r->print(&mt('Diffs with Current Version').'</a>');
1.139     albertel 2229: 	}
1.240     raeburn  2230:         
                   2231:         $r->print(&Apache::lonhtmlcommon::row_closure(1)
                   2232:                  .&Apache::lonhtmlcommon::end_pick_box()
                   2233:                  );
1.11      www      2234:   
1.268     www      2235: # ---------------------- Publishing from $fn to $thistarget with $thisembstyle.
1.2       www      2236: 
1.192     albertel 2237: 	unless ($env{'form.phase'} eq 'two') {
1.185     www      2238: # ---------------------------------------------------------- Parse for problems
1.189     albertel 2239: 	    my ($warningcount,$errorcount);
                   2240: 	    if ($thisembstyle eq 'ssi') {
1.268     www      2241: 		($warningcount,$errorcount)=&checkonthis($r,$fn);
1.189     albertel 2242: 	    }
                   2243: 	    unless ($errorcount) {
1.187     www      2244: 		my ($outstring,$error)=
1.272     www      2245: 		    &publish($docroot.$fn,$docroot.$thistarget,$thisembstyle);
1.246     bisitz   2246: 		$r->print($outstring);
1.187     www      2247: 	    } else {
1.239     bisitz   2248: 		$r->print('<h3 class="LC_error">'.
1.189     albertel 2249: 			  &mt('The document contains errors and cannot be published.').
1.187     www      2250: 			  '</h3>');
                   2251: 	    }
1.139     albertel 2252: 	} else {
1.272     www      2253: 	    &phasetwo($r,$docroot.$fn,$docroot.$thistarget,$thisembstyle,$thisdistarget); 
1.139     albertel 2254: 	}
                   2255:     }
1.208     albertel 2256:     $r->print(&Apache::loncommon::end_page());
1.15      www      2257: 
1.139     albertel 2258:     return OK;
1.1       www      2259: }
                   2260: 
                   2261: 1;
                   2262: __END__
                   2263: 
1.89      matthew  2264: =pod
1.126     bowersj2 2265: 
                   2266: =back
1.66      harris41 2267: 
                   2268: =back
                   2269: 
1.89      matthew  2270: =cut
1.66      harris41 2271: 

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