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

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

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