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

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

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