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

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

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