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

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

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