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

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

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