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

1.1       www         1: # The LearningOnline Network with CAPA
                      2: # Publication Handler
1.54      albertel    3: #
1.95    ! www         4: # $Id: lonpublisher.pm,v 1.94 2002/09/10 14:52:35 harris41 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.1       www        28: # 
                     29: # (TeX Content Handler
                     30: #
                     31: # 05/29/00,05/30,10/11 Gerd Kortemeyer)
                     32: #
1.15      www        33: # 11/28,11/29,11/30,12/01,12/02,12/04,12/23 Gerd Kortemeyer
1.20      www        34: # 03/23 Guy Albertelli
1.23      www        35: # 03/24,03/29,04/03 Gerd Kortemeyer
1.24      harris41   36: # 04/16/2001 Scott Harrison
1.27      www        37: # 05/03,05/05,05/07 Gerd Kortemeyer
1.30      harris41   38: # 05/28/2001 Scott Harrison
1.51      www        39: # 06/23,08/07,08/11,8/13,8/17,8/18,8/24,9/26,10/16 Gerd Kortemeyer
1.58      www        40: # 12/04,12/05 Guy Albertelli
                     41: # 12/05 Gerd Kortemeyer
1.62      www        42: # 12/05 Guy Albertelli
1.64      www        43: # 12/06,12/07 Gerd Kortemeyer
1.66      harris41   44: # 12/15,12/16 Scott Harrison
1.67      www        45: # 12/25 Gerd Kortemeyer
1.71      www        46: # YEAR=2002
                     47: # 1/16,1/17 Scott Harrison
                     48: # 1/17 Gerd Kortemeyer
1.65      harris41   49: #
                     50: ###
                     51: 
                     52: ###############################################################################
                     53: ##                                                                           ##
                     54: ## ORGANIZATION OF THIS PERL MODULE                                          ##
                     55: ##                                                                           ##
                     56: ## 1. Modules used by this module                                            ##
                     57: ## 2. Various subroutines                                                    ##
                     58: ## 3. Publication Step One                                                   ##
                     59: ## 4. Phase Two                                                              ##
                     60: ## 5. Main Handler                                                           ##
                     61: ##                                                                           ##
                     62: ###############################################################################
1.1       www        63: 
1.90      matthew    64: 
                     65: ######################################################################
                     66: ######################################################################
                     67: 
                     68: =pod 
                     69: 
1.94      harris41   70: =head1 NAME
1.90      matthew    71: 
                     72: lonpublisher - LON-CAPA publishing handler
                     73: 
1.94      harris41   74: =head1 SYNOPSIS
1.90      matthew    75: 
1.94      harris41   76: B<lonpublisher> is used by B<mod_perl> inside B<Apache>.  This is the
                     77: invocation by F<loncapa_apache.conf>:
                     78: 
                     79:   <Location /adm/publish>
                     80:   PerlAccessHandler       Apache::lonacc
                     81:   SetHandler perl-script
                     82:   PerlHandler Apache::lonpublisher
                     83:   ErrorDocument     403 /adm/login
                     84:   ErrorDocument     404 /adm/notfound.html
                     85:   ErrorDocument     406 /adm/unauthorized.html
                     86:   ErrorDocument     500 /adm/errorhandler
                     87:   </Location>
                     88: 
                     89: =head1 DESCRIPTION
                     90: 
                     91: B<lonpublisher> takes the proper steps to add resources to the LON-CAPA
1.90      matthew    92: digital library.  This includes updating the metadata table in the
                     93: LON-CAPA database.
                     94: 
1.94      harris41   95: B<lonpublisher> is many things to many people.  
1.90      matthew    96: 
                     97: This module publishes a file.  This involves gathering metadata,
                     98: versioning the file, copying file from construction space to
                     99: publication space, and copying metadata from construction space
                    100: to publication space.
                    101: 
1.94      harris41  102: =head2 SUBROUTINES
                    103: 
                    104: Many of the undocumented subroutines implement various magical
                    105: parsing shortcuts.
1.90      matthew   106: 
                    107: =over 4
                    108: 
                    109: =cut
                    110: 
                    111: ######################################################################
                    112: ######################################################################
                    113: 
                    114: 
1.1       www       115: package Apache::lonpublisher;
                    116: 
1.65      harris41  117: # ------------------------------------------------- modules used by this module
1.1       www       118: use strict;
                    119: use Apache::File;
1.13      www       120: use File::Copy;
1.2       www       121: use Apache::Constants qw(:common :http :methods);
1.76      albertel  122: use HTML::LCParser;
1.4       www       123: use Apache::lonxml;
1.17      albertel  124: use Apache::lonhomework;
1.27      www       125: use Apache::loncacc;
1.24      harris41  126: use DBI;
1.65      harris41  127: use Apache::lonnet();
                    128: use Apache::loncommon();
1.89      matthew   129: use Apache::lonmysql;
1.2       www       130: 
1.3       www       131: my %addid;
1.5       www       132: my %nokey;
1.10      www       133: 
1.7       www       134: my %metadatafields;
                    135: my %metadatakeys;
                    136: 
1.12      www       137: my $docroot;
                    138: 
1.27      www       139: my $cuname;
                    140: my $cudom;
                    141: 
1.90      matthew   142: #########################################
                    143: #########################################
                    144: 
                    145: =pod
                    146: 
1.94      harris41  147: =item B<metaeval>
                    148: 
                    149: Evaluates a string that contains metadata.  This subroutine
                    150: stores values inside I<%metadatafields> and I<%metadatakeys>.
                    151: The hash key is a I<$unikey> corresponding to a unique id
                    152: that is descriptive of the parser location inside the XML tree.
                    153: 
                    154: Parameters:
                    155: 
                    156: =over 4
1.90      matthew   157: 
1.94      harris41  158: =item I<$metastring>
                    159: 
                    160: A string that contains metadata.
                    161: 
                    162: =back
                    163: 
                    164: Returns:
                    165: 
                    166: nothing
1.90      matthew   167: 
                    168: =cut
                    169: 
                    170: #########################################
                    171: #########################################
1.7       www       172: sub metaeval {
                    173:     my $metastring=shift;
                    174:    
1.76      albertel  175:         my $parser=HTML::LCParser->new(\$metastring);
1.7       www       176:         my $token;
                    177:         while ($token=$parser->get_token) {
                    178:            if ($token->[0] eq 'S') {
                    179: 	      my $entry=$token->[1];
                    180:               my $unikey=$entry;
1.32      www       181:               if (defined($token->[2]->{'package'})) { 
                    182:                   $unikey.='_package_'.$token->[2]->{'package'};
                    183:               } 
1.7       www       184:               if (defined($token->[2]->{'part'})) { 
                    185:                  $unikey.='_'.$token->[2]->{'part'}; 
                    186: 	      }
1.32      www       187:               if (defined($token->[2]->{'id'})) { 
1.49      www       188:                   $unikey.='_'.$token->[2]->{'id'};
1.32      www       189:               } 
1.7       www       190:               if (defined($token->[2]->{'name'})) { 
                    191:                  $unikey.='_'.$token->[2]->{'name'}; 
                    192: 	      }
1.65      harris41  193:               foreach (@{$token->[3]}) {
1.7       www       194: 		  $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
                    195:                   if ($metadatakeys{$unikey}) {
                    196: 		      $metadatakeys{$unikey}.=','.$_;
                    197:                   } else {
                    198:                       $metadatakeys{$unikey}=$_;
                    199:                   }
1.65      harris41  200:               }
1.7       www       201:               if ($metadatafields{$unikey}) {
1.8       www       202: 		  my $newentry=$parser->get_text('/'.$entry);
1.41      www       203:                   unless (($metadatafields{$unikey}=~/$newentry/) ||
                    204:                           ($newentry eq '')) {
1.8       www       205:                      $metadatafields{$unikey}.=', '.$newentry;
                    206: 		  }
1.7       www       207: 	      } else {
                    208:                  $metadatafields{$unikey}=$parser->get_text('/'.$entry);
                    209:               }
                    210:           }
                    211:        }
                    212: }
                    213: 
1.90      matthew   214: #########################################
                    215: #########################################
                    216: 
                    217: =pod
                    218: 
1.94      harris41  219: =item B<metaread>
1.90      matthew   220: 
                    221: Read a metadata file
                    222: 
1.94      harris41  223: Parameters:
                    224: 
                    225: =over
                    226: 
                    227: =item I<$logfile>
                    228: 
                    229: File output stream to output errors and warnings to.
                    230: 
                    231: =item I<$fn>
                    232: 
                    233: File name (including path).
                    234: 
                    235: =back
                    236: 
                    237: Returns:
                    238: 
                    239: =over 4
                    240: 
                    241: =item Scalar string (if successful)
                    242: 
                    243: XHTML text that indicates successful reading of the metadata.
                    244: 
                    245: =back
                    246: 
1.90      matthew   247: =cut
                    248: 
                    249: #########################################
                    250: #########################################
1.7       www       251: sub metaread {
                    252:     my ($logfile,$fn)=@_;
                    253:     unless (-e $fn) {
1.94      harris41  254: 	print($logfile 'No file '.$fn."\n");
1.7       www       255:         return '<br><b>No file:</b> <tt>'.$fn.'</tt>';
                    256:     }
1.94      harris41  257:     print($logfile 'Processing '.$fn."\n");
1.7       www       258:     my $metastring;
                    259:     {
                    260:      my $metafh=Apache::File->new($fn);
                    261:      $metastring=join('',<$metafh>);
                    262:     }
                    263:     &metaeval($metastring);
                    264:     return '<br><b>Processed file:</b> <tt>'.$fn.'</tt>';
                    265: }
                    266: 
1.90      matthew   267: #########################################
                    268: #########################################
                    269: 
                    270: =pod
                    271: 
1.94      harris41  272: =item B<sqltime>
1.90      matthew   273: 
                    274: Convert 'time' format into a datetime sql format
                    275: 
1.94      harris41  276: Parameters:
                    277: 
                    278: =over 4
                    279: 
                    280: =item I<$timef>
                    281: 
                    282: Seconds since 00:00:00 UTC, January 1, 1970.
                    283: 
                    284: =back
                    285: 
                    286: Returns:
                    287: 
                    288: =over 4
                    289: 
                    290: =item Scalar string
                    291: 
                    292: MySQL-compatible datetime string.
                    293: 
                    294: =back
                    295: 
1.90      matthew   296: =cut
                    297: 
                    298: #########################################
                    299: #########################################
1.25      harris41  300: sub sqltime {
1.70      harris41  301:     my $timef=shift @_;
1.25      harris41  302:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1.70      harris41  303: 	localtime($timef);
1.25      harris41  304:     $mon++; $year+=1900;
                    305:     return "$year-$mon-$mday $hour:$min:$sec";
                    306: }
                    307: 
1.12      www       308: 
1.90      matthew   309: #########################################
                    310: #########################################
                    311: 
                    312: =pod
                    313: 
1.94      harris41  314: =item Form-field-generating subroutines.
                    315: 
                    316: For input parameters, these subroutines take in values
                    317: such as I<$name>, I<$value> and other form field metadata.
                    318: The output (scalar string that is returned) is an XHTML
                    319: string which presents the form field (foreseeably inside
                    320: <form></form> tags).
1.90      matthew   321: 
                    322: =over 4
                    323: 
1.94      harris41  324: =item B<textfield>
1.90      matthew   325: 
1.94      harris41  326: =item B<hiddenfield>
1.90      matthew   327: 
1.94      harris41  328: =item B<selectbox>
1.90      matthew   329: 
                    330: =back
                    331: 
                    332: =cut
                    333: 
                    334: #########################################
                    335: #########################################
1.8       www       336: sub textfield {
1.10      www       337:     my ($title,$name,$value)=@_;
1.8       www       338:     return "\n<p><b>$title:</b><br>".
1.94      harris41  339:            '<input type="text" name="'.$name.'" size=80 value="'.$value.'" />';
1.11      www       340: }
                    341: 
                    342: sub hiddenfield {
                    343:     my ($name,$value)=@_;
1.94      harris41  344:     return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
1.8       www       345: }
                    346: 
1.9       www       347: sub selectbox {
1.65      harris41  348:     my ($title,$name,$value,$functionref,@idlist)=@_;
                    349:     my $uctitle=uc($title);
                    350:     my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
                    351: 	"</b></font><br />".'<select name="'.$name.'">';
                    352:     foreach (@idlist) {
                    353:         $selout.='<option value=\''.$_.'\'';
                    354:         if ($_ eq $value) {
                    355: 	    $selout.=' selected>'.&{$functionref}($_).'</option>';
                    356: 	}
                    357:         else {$selout.='>'.&{$functionref}($_).'</option>';}
                    358:     }
1.10      www       359:     return $selout.'</select>';
1.9       www       360: }
                    361: 
1.90      matthew   362: #########################################
                    363: #########################################
                    364: 
                    365: =pod
                    366: 
1.94      harris41  367: =item B<urlfixup>
1.90      matthew   368: 
                    369: Fix up a url?  First step of publication
1.12      www       370: 
1.90      matthew   371: =cut
                    372: 
                    373: #########################################
                    374: #########################################
1.34      www       375: sub urlfixup {
1.35      www       376:     my ($url,$target)=@_;
1.39      www       377:     unless ($url) { return ''; }
1.68      albertel  378:     #javascript code needs no fixing
                    379:     if ($url =~ /^javascript:/i) { return $url; }
1.69      albertel  380:     if ($url =~ /^mailto:/i) { return $url; }
1.68      albertel  381:     #internal document links need no fixing
                    382:     if ($url =~ /^\#/) { return $url; } 
1.35      www       383:     my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
1.65      harris41  384:     foreach (values %Apache::lonnet::hostname) {
1.35      www       385: 	if ($_ eq $host) {
                    386: 	    $url=~s/^http\:\/\///;
                    387:             $url=~s/^$host//;
                    388:         }
1.65      harris41  389:     }
1.40      www       390:     if ($url=~/^http\:\/\//) { return $url; }
1.35      www       391:     $url=~s/\~$cuname/res\/$cudom\/$cuname/;
1.71      www       392:     return $url;
                    393: }
                    394: 
1.90      matthew   395: #########################################
                    396: #########################################
                    397: 
                    398: =pod
                    399: 
1.94      harris41  400: =item B<absoluteurl>
1.90      matthew   401: 
1.94      harris41  402: Currently undocumented.
1.90      matthew   403: 
                    404: =cut
1.71      www       405: 
1.90      matthew   406: #########################################
                    407: #########################################
1.71      www       408: sub absoluteurl {
                    409:     my ($url,$target)=@_;
                    410:     unless ($url) { return ''; }
1.35      www       411:     if ($target) {
                    412: 	$target=~s/\/[^\/]+$//;
                    413:        $url=&Apache::lonnet::hreflocation($target,$url);
                    414:     }
                    415:     return $url;
1.34      www       416: }
                    417: 
1.90      matthew   418: #########################################
                    419: #########################################
                    420: 
                    421: =pod
                    422: 
1.94      harris41  423: =item B<set_allow>
1.90      matthew   424: 
                    425: Currently undocumented    
                    426: 
                    427: =cut
                    428: 
                    429: #########################################
                    430: #########################################
1.81      albertel  431: sub set_allow {
                    432:     my ($allow,$logfile,$target,$tag,$oldurl)=@_;
                    433:     my $newurl=&urlfixup($oldurl,$target);
                    434:     my $return_url=$oldurl;
                    435:     print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
                    436:     if ($newurl ne $oldurl) {
                    437: 	$return_url=$newurl;
                    438: 	print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
                    439:     }
                    440:     if (($newurl !~ /^javascript:/i) &&
                    441: 	($newurl !~ /^mailto:/i) &&
                    442: 	($newurl !~ /^http:/i) &&
                    443: 	($newurl !~ /^\#/)) {
                    444: 	$$allow{&absoluteurl($newurl,$target)}=1;
                    445:     }
                    446:     return $return_url
                    447: }
                    448: 
1.90      matthew   449: #########################################
                    450: #########################################
                    451: 
                    452: =pod
                    453: 
1.94      harris41  454: =item B<get_subscribed_hosts>
1.90      matthew   455: 
                    456: Currently undocumented    
                    457: 
                    458: =cut
                    459: 
                    460: #########################################
                    461: #########################################
1.85      albertel  462: sub get_subscribed_hosts {
                    463:     my ($target)=@_;
                    464:     my @subscribed;
                    465:     my $filename;
                    466:     $target=~/(.*)\/([^\/]+)$/;
                    467:     my $srcf=$2;
                    468:     opendir(DIR,$1);
                    469:     while ($filename=readdir(DIR)) {
                    470: 	if ($filename=~/$srcf\.(\w+)$/) {
                    471: 	    my $subhost=$1;
                    472: 	    if ($subhost ne 'meta' && $subhost ne 'subscription') {
                    473: 		push(@subscribed,$subhost);
                    474: 	    }
                    475: 	}
                    476:     }
                    477:     closedir(DIR);
                    478:     my $sh;
                    479:     if ( $sh=Apache::File->new("$target.subscription") ) {
                    480: 	&Apache::lonnet::logthis("opened $target.subscription");
                    481: 	while (my $subline=<$sh>) {
                    482: 	    &Apache::lonnet::logthis("Trying $subline");
                    483: 	    if ($subline =~ /(^\w+):/) { push(@subscribed,$1); } else {
                    484: 		&Apache::lonnet::logthis("No Match for $subline");
                    485: 	    }
                    486: 	}
                    487:     } else {
1.94      harris41  488: 	&Apache::lonnet::logthis("Unable to open $target.subscription");
1.85      albertel  489:     }
                    490:     &Apache::lonnet::logthis("Got list of ".join(':',@subscribed));
                    491:     return @subscribed;
                    492: }
                    493: 
1.86      albertel  494: 
1.90      matthew   495: #########################################
                    496: #########################################
                    497: 
                    498: =pod
                    499: 
1.94      harris41  500: =item B<get_max_ids_indices>
1.90      matthew   501: 
                    502: Currently undocumented    
                    503: 
                    504: =cut
                    505: 
                    506: #########################################
                    507: #########################################
1.86      albertel  508: sub get_max_ids_indices {
                    509:     my ($content)=@_;
                    510:     my $maxindex=10;
                    511:     my $maxid=10;
                    512:     my $needsfixup=0;
                    513: 
                    514:     my $parser=HTML::LCParser->new($content);
                    515:     my $token;
                    516:     while ($token=$parser->get_token) {
                    517: 	if ($token->[0] eq 'S') {
                    518: 	    my $counter;
                    519: 	    if ($counter=$addid{$token->[1]}) {
                    520: 		if ($counter eq 'id') {
                    521: 		    if (defined($token->[2]->{'id'})) {
                    522: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
                    523: 		    } else {
                    524: 			$needsfixup=1;
                    525: 		    }
                    526: 		} else {
                    527: 		    if (defined($token->[2]->{'index'})) {
                    528: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
                    529: 		    } else {
                    530: 			$needsfixup=1;
                    531: 		    }
                    532: 		}
                    533: 	    }
                    534: 	}
                    535:     }
                    536:     return ($needsfixup,$maxid,$maxindex);
                    537: }
                    538: 
1.90      matthew   539: #########################################
                    540: #########################################
                    541: 
                    542: =pod
                    543: 
1.94      harris41  544: =item B<get_all_text_unbalanced>
1.90      matthew   545: 
                    546: Currently undocumented    
                    547: 
                    548: =cut
                    549: 
                    550: #########################################
                    551: #########################################
1.87      albertel  552: sub get_all_text_unbalanced {
                    553:     #there is a copy of this in lonxml.pm
                    554:     my($tag,$pars)= @_;
                    555:     my $token;
                    556:     my $result='';
                    557:     $tag='<'.$tag.'>';
                    558:     while ($token = $$pars[-1]->get_token) {
                    559: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
                    560: 	    $result.=$token->[1];
                    561: 	} elsif ($token->[0] eq 'PI') {
                    562: 	    $result.=$token->[2];
                    563: 	} elsif ($token->[0] eq 'S') {
                    564: 	    $result.=$token->[4];
                    565: 	} elsif ($token->[0] eq 'E')  {
                    566: 	    $result.=$token->[2];
                    567: 	}
                    568: 	if ($result =~ /(.*)$tag(.*)/) {
1.88      albertel  569: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
                    570: 	    #&Apache::lonnet::logthis('Result is :'.$1);
1.87      albertel  571: 	    $result=$1;
                    572: 	    my $redo=$tag.$2;
                    573: 	    push (@$pars,HTML::LCParser->new(\$redo));
                    574: 	    $$pars[-1]->xml_mode('1');
                    575: 	    last;
                    576: 	}
                    577:     }
                    578:     return $result
                    579: }
                    580: 
1.90      matthew   581: #########################################
                    582: #########################################
                    583: 
                    584: =pod
                    585: 
1.94      harris41  586: =item B<fix_ids_and_indices>
1.90      matthew   587: 
                    588: Currently undocumented    
                    589: 
                    590: =cut
                    591: 
                    592: #########################################
                    593: #########################################
1.87      albertel  594: #Arguably this should all be done as a lonnet::ssi instead
1.86      albertel  595: sub fix_ids_and_indices {
                    596:     my ($logfile,$source,$target)=@_;
                    597: 
                    598:     my %allow;
                    599:     my $content;
                    600:     {
                    601: 	my $org=Apache::File->new($source);
                    602: 	$content=join('',<$org>);
                    603:     }
                    604: 
                    605:     my ($needsfixup,$maxid,$maxindex)=&get_max_ids_indices(\$content);
                    606: 
                    607:     if ($needsfixup) {
                    608: 	print $logfile "Needs ID and/or index fixup\n".
                    609: 	    "Max ID   : $maxid (min 10)\n".
                    610:                 "Max Index: $maxindex (min 10)\n";
                    611:     }
                    612:     my $outstring='';
                    613:     my @parser;
                    614:     $parser[0]=HTML::LCParser->new(\$content);
                    615:     $parser[-1]->xml_mode(1);
                    616:     my $token;
                    617:     while (@parser) {
                    618: 	while ($token=$parser[-1]->get_token) {
                    619: 	    if ($token->[0] eq 'S') {
                    620: 		my $counter;
                    621: 		my $tag=$token->[1];
                    622: 		my $lctag=lc($tag);
                    623: 		if ($lctag eq 'allow') {
                    624: 		    $allow{$token->[2]->{'src'}}=1;
                    625: 		    next;
                    626: 		}
                    627: 		my %parms=%{$token->[2]};
                    628: 		$counter=$addid{$tag};
                    629: 		if (!$counter) { $counter=$addid{$lctag}; }
                    630: 		if ($counter) {
                    631: 		    if ($counter eq 'id') {
                    632: 			unless (defined($parms{'id'})) {
                    633: 			    $maxid++;
                    634: 			    $parms{'id'}=$maxid;
                    635: 			    print $logfile 'ID: '.$tag.':'.$maxid."\n";
                    636: 			}
                    637: 		    } elsif ($counter eq 'index') {
                    638: 			unless (defined($parms{'index'})) {
                    639: 			    $maxindex++;
                    640: 			    $parms{'index'}=$maxindex;
                    641: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
                    642: 			}
                    643: 		    }
                    644: 		}
                    645: 		foreach my $type ('src','href','background','bgimg') {
                    646: 		    foreach my $key (keys(%parms)) {
                    647: 			if ($key =~ /^$type$/i) {
                    648: 			    $parms{$key}=&set_allow(\%allow,$logfile,
                    649: 						    $target,$tag,
                    650: 						    $parms{$key});
                    651: 			}
                    652: 		    }
                    653: 		}
                    654: 		# probably a <randomlabel> image type <label>
                    655: 		if ($lctag eq 'label' && defined($parms{'description'})) {
                    656: 		    my $next_token=$parser[-1]->get_token();
                    657: 		    if ($next_token->[0] eq 'T') {
                    658: 			$next_token->[1]=&set_allow(\%allow,$logfile,
                    659: 						    $target,$tag,
                    660: 						    $next_token->[1]);
                    661: 		    }
                    662: 		    $parser[-1]->unget_token($next_token);
                    663: 		}
                    664: 		if ($lctag eq 'applet') {
                    665: 		    my $codebase='';
                    666: 		    if (defined($parms{'codebase'})) {
                    667: 			my $oldcodebase=$parms{'codebase'};
                    668: 			unless ($oldcodebase=~/\/$/) {
                    669: 			    $oldcodebase.='/';
                    670: 			}
                    671: 			$codebase=&urlfixup($oldcodebase,$target);
                    672: 			$codebase=~s/\/$//;    
                    673: 			if ($codebase ne $oldcodebase) {
                    674: 			    $parms{'codebase'}=$codebase;
                    675: 			    print $logfile 'URL codebase: '.$tag.':'.
                    676: 				$oldcodebase.' - '.
                    677: 				    $codebase."\n";
                    678: 			}
                    679: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
                    680: 		    } else {
                    681: 			foreach ('archive','code','object') {
                    682: 			    if (defined($parms{$_})) {
                    683: 				my $oldurl=$parms{$_};
                    684: 				my $newurl=&urlfixup($oldurl,$target);
                    685: 				$newurl=~s/\/[^\/]+$/\/\*/;
                    686: 				print $logfile 'Allow: applet '.$_.':'.
                    687: 				    $oldurl.' allows '.
                    688: 					$newurl."\n";
                    689: 				$allow{&absoluteurl($newurl,$target)}=1;
                    690: 			    }
                    691: 			}
                    692: 		    }
                    693: 		}
                    694: 		my $newparmstring='';
                    695: 		my $endtag='';
                    696: 		foreach (keys %parms) {
                    697: 		    if ($_ eq '/') {
                    698: 			$endtag=' /';
                    699: 		    } else { 
                    700: 			my $quote=($parms{$_}=~/\"/?"'":'"');
                    701: 			$newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
                    702: 		    }
                    703: 		}
                    704: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
                    705: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
1.87      albertel  706: 		if ($lctag eq 'm') {
                    707: 		    $outstring.=&get_all_text_unbalanced('/m',\@parser);
                    708: 		}
1.86      albertel  709: 	    } elsif ($token->[0] eq 'E') {
                    710: 		if ($token->[2]) {
                    711: 		    unless ($token->[1] eq 'allow') {
                    712: 			$outstring.='</'.$token->[1].'>';
                    713: 		    }
                    714: 		}
                    715: 	    } else {
                    716: 		$outstring.=$token->[1];
                    717: 	    }
                    718: 	}
                    719: 	pop(@parser);
                    720:     }
                    721: 
                    722:     if ($needsfixup) {
                    723: 	print $logfile "End of ID and/or index fixup\n".
                    724: 	    "Max ID   : $maxid (min 10)\n".
                    725: 		"Max Index: $maxindex (min 10)\n";
                    726:     } else {
                    727: 	print $logfile "Does not need ID and/or index fixup\n";
                    728:     }
                    729: 
                    730:     return ($outstring,%allow);
                    731: }
                    732: 
1.89      matthew   733: #########################################
                    734: #########################################
                    735: 
                    736: =pod
                    737: 
1.94      harris41  738: =item B<store_metadata>
1.89      matthew   739: 
                    740: Store the metadata in the metadata table in the loncapa database.
                    741: Uses lonmysql to access the database.
                    742: 
                    743: Inputs: \%metadata
                    744: 
                    745: Returns: (error,status).  error is undef on success, status is undef on error.
                    746: 
                    747: =cut
                    748: 
                    749: #########################################
                    750: #########################################
                    751: sub store_metadata {
                    752:     my %metadata = %{shift()};
                    753:     my $error;
                    754:     # Determine if the table exists
                    755:     my $status = &Apache::lonmysql::check_table('metadata');
                    756:     if (! defined($status)) {
                    757:         $error='<font color="red">WARNING: Cannot connect to '.
                    758:             'database!</font>';
                    759:         &Apache::lonnet::logthis($error);
                    760:         return ($error,undef);
                    761:     }
                    762:     if ($status == 0) {
                    763:         # It would be nice to actually create the table....
                    764:         $error ='<font color="red">WARNING: The metadata table does not '.
                    765:             'exist in the LON-CAPA database.</font>';
                    766:         &Apache::lonnet::logthis($error);
                    767:         return ($error,undef);
                    768:     }
                    769:     # Remove old value from table
                    770:     $status = &Apache::lonmysql::remove_from_table
                    771:         ('metadata','url',$metadata{'url'});
                    772:     if (! defined($status)) {
                    773:         $error = '<font color="red">Error when removing old values from '.
                    774:             'metadata table in LON-CAPA database.</font>';
                    775:         &Apache::lonnet::logthis($error);
                    776:         return ($error,undef);
                    777:     }
                    778:     # Store data in table.
                    779:     $status = &Apache::lonmysql::store_row('metadata',\%metadata);
                    780:     if (! defined($status)) {
                    781:         $error='<font color="red">Error occured storing new values in '.
                    782:             'metadata table in LON-CAPA database</font>';
                    783:         &Apache::lonnet::logthis($error);
                    784:         return ($error,undef);
                    785:     }
                    786:     return (undef,$status);
                    787: }
                    788: 
1.90      matthew   789: #########################################
                    790: #########################################
                    791: 
                    792: =pod
                    793: 
1.94      harris41  794: =item B<publish>
                    795: 
                    796: This is the workhorse function of this module.  This subroutine generates
                    797: backup copies, performs any automatic processing (prior to publication,
                    798: especially for rat and ssi files),
1.90      matthew   799: 
1.94      harris41  800: I<Additional documentation needed.>
1.90      matthew   801: 
                    802: =cut
                    803: 
                    804: #########################################
                    805: #########################################
1.2       www       806: sub publish {
1.50      www       807: 
1.2       www       808:     my ($source,$target,$style)=@_;
                    809:     my $logfile;
1.4       www       810:     my $scrout='';
1.23      www       811:     my $allmeta='';
                    812:     my $content='';
1.36      www       813:     my %allow=();
1.4       www       814: 
1.2       www       815:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1.7       www       816: 	return 
                    817:          '<font color=red>No write permission to user directory, FAIL</font>';
1.2       www       818:     }
                    819:     print $logfile 
1.11      www       820: "\n\n================= Publish ".localtime()." Phase One  ================\n";
1.2       www       821: 
1.3       www       822:     if (($style eq 'ssi') || ($style eq 'rat')) {
                    823: # ------------------------------------------------------- This needs processing
1.4       www       824: 
                    825: # ----------------------------------------------------------------- Backup Copy
1.3       www       826: 	my $copyfile=$source.'.save';
1.13      www       827:         if (copy($source,$copyfile)) {
1.3       www       828: 	    print $logfile "Copied original file to ".$copyfile."\n";
                    829:         } else {
1.13      www       830: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
                    831:           return "<font color=red>Failed to write backup copy, $!,FAIL</font>";
1.3       www       832:         }
1.4       www       833: # ------------------------------------------------------------- IDs and indices
1.86      albertel  834: 	
                    835: 	my $outstring;
                    836: 	($outstring,%allow)=&fix_ids_and_indices($logfile,$source,$target);
1.36      www       837: # ------------------------------------------------------------ Construct Allows
1.62      www       838:     
1.44      www       839: 	$scrout.='<h3>Dependencies</h3>';
1.62      www       840:         my $allowstr='';
1.73      albertel  841:         foreach (sort(keys(%allow))) {
1.59      www       842: 	   my $thisdep=$_;
1.73      albertel  843: 	   if ($thisdep !~ /[^\s]/) { next; }
1.62      www       844:            unless ($style eq 'rat') { 
                    845:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
                    846: 	   }
1.44      www       847:            $scrout.='<br>';
1.59      www       848:            unless ($thisdep=~/\*/) {
                    849: 	       $scrout.='<a href="'.$thisdep.'">';
1.44      www       850:            }
1.59      www       851:            $scrout.='<tt>'.$thisdep.'</tt>';
                    852:            unless ($thisdep=~/\*/) {
1.44      www       853: 	       $scrout.='</a>';
1.59      www       854:                if (
                    855:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                    856:                                             $thisdep.'.meta') eq '-1') {
1.94      harris41  857: 		   $scrout.= ' - <font color="red">Currently not available'.
                    858: 		       '</font>';
1.59      www       859:                } else {
                    860:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
                    861:                              &Apache::lonnet::declutter($thisdep).'___usage'
                    862:                                  => time);
                    863:                    $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
                    864:                    if ((defined($1)) && (defined($2))) {
1.92      albertel  865:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
                    866: 					   $1,$2);
1.59      www       867: 		   }
                    868: 	       }
1.44      www       869:            }
1.65      harris41  870:         }
1.83      www       871:         $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
1.62      www       872: 
1.76      albertel  873: 	#Encode any High ASCII characters
                    874: 	$outstring=&HTML::Entities::encode($outstring,"\200-\377");
1.94      harris41  875: # ------------------------------------------------------------- Write modified.
1.37      www       876: 
1.4       www       877:         {
                    878:           my $org;
                    879:           unless ($org=Apache::File->new('>'.$source)) {
                    880:              print $logfile "No write permit to $source\n";
1.7       www       881:              return 
1.94      harris41  882: 		 '<font color="red">No write permission to '.$source.
                    883: 		 ', FAIL</font>';
1.4       www       884: 	  }
1.94      harris41  885:           print($org $outstring);
1.4       www       886:         }
                    887: 	  $content=$outstring;
1.34      www       888: 
1.37      www       889:     }
1.94      harris41  890: # -------------------------------------------- Initial step done, now metadata.
1.7       www       891: 
1.94      harris41  892: # --------------------------------------- Storage for metadata keys and fields.
1.7       www       893: 
1.8       www       894:      %metadatafields=();
                    895:      %metadatakeys=();
                    896:      
                    897:      my %oldparmstores=();
1.44      www       898:      
1.84      bowersj2  899:      
                    900:      $scrout.='<h3>Metadata Information ' .
                    901:        Apache::loncommon::help_open_topic("Metadata_Description")
                    902:        . '</h3>';
1.7       www       903: 
                    904: # ------------------------------------------------ First, check out environment
1.8       www       905:      unless (-e $source.'.meta') {
1.7       www       906:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
                    907: 	                          $ENV{'environment.middlename'}.' '.
                    908: 		                  $ENV{'environment.lastname'}.' '.
                    909: 		                  $ENV{'environment.generation'};
1.8       www       910:         $metadatafields{'author'}=~s/\s+/ /g;
                    911:         $metadatafields{'author'}=~s/\s+$//;
1.27      www       912:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
1.7       www       913: 
                    914: # ------------------------------------------------ Check out directory hierachy
                    915: 
                    916:         my $thisdisfn=$source;
1.27      www       917:         $thisdisfn=~s/^\/home\/$cuname\///;
1.7       www       918: 
                    919:         my @urlparts=split(/\//,$thisdisfn);
                    920:         $#urlparts--;
                    921: 
1.27      www       922:         my $currentpath='/home/'.$cuname.'/';
1.7       www       923: 
1.65      harris41  924:         foreach (@urlparts) {
1.7       www       925: 	    $currentpath.=$_.'/';
                    926:             $scrout.=&metaread($logfile,$currentpath.'default.meta');
1.65      harris41  927:         }
1.7       www       928: 
                    929: # ------------------- Clear out parameters and stores (there should not be any)
                    930: 
1.65      harris41  931:         foreach (keys %metadatafields) {
1.7       www       932: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                    933: 		delete $metadatafields{$_};
                    934:             }
1.65      harris41  935:         }
1.7       www       936: 
1.8       www       937:     } else {
1.7       www       938: # ---------------------- Read previous metafile, remember parameters and stores
                    939: 
                    940:         $scrout.=&metaread($logfile,$source.'.meta');
                    941: 
1.65      harris41  942:         foreach (keys %metadatafields) {
1.7       www       943: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                    944:                 $oldparmstores{$_}=1;
                    945: 		delete $metadatafields{$_};
                    946:             }
1.65      harris41  947:         }
1.7       www       948:         
1.8       www       949:     }
1.7       www       950: 
1.4       www       951: # -------------------------------------------------- Parse content for metadata
1.37      www       952:     if ($style eq 'ssi') {
1.42      www       953:         my $oldenv=$ENV{'request.uri'};
                    954: 
                    955:         $ENV{'request.uri'}=$target;
1.82      albertel  956:         $allmeta=Apache::lonxml::xmlparse(undef,'meta',$content);
1.42      www       957:         $ENV{'request.uri'}=$oldenv;
1.32      www       958: 
1.19      albertel  959:         &metaeval($allmeta);
1.37      www       960:     }
1.7       www       961: # ---------------- Find and document discrepancies in the parameters and stores
                    962: 
                    963:         my $chparms='';
1.65      harris41  964:         foreach (sort keys %metadatafields) {
1.7       www       965: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
                    966:                 unless ($_=~/\.\w+$/) { 
                    967:                    unless ($oldparmstores{$_}) {
                    968: 		      print $logfile 'New: '.$_."\n";
                    969:                       $chparms.=$_.' ';
                    970:                    }
                    971: 	        }
                    972:             }
1.65      harris41  973:         }
1.7       www       974:         if ($chparms) {
                    975: 	    $scrout.='<p><b>New parameters or stored values:</b> '.
                    976:                      $chparms;
                    977:         }
                    978: 
1.70      harris41  979:         $chparms='';
1.65      harris41  980:         foreach (sort keys %oldparmstores) {
1.7       www       981: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
1.33      www       982:                 unless (($metadatafields{$_.'.name'}) ||
                    983:                         ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
1.7       www       984: 		    print $logfile 'Obsolete: '.$_."\n";
                    985:                     $chparms.=$_.' ';
                    986:                 }
                    987:             }
1.65      harris41  988:         }
1.7       www       989:         if ($chparms) {
                    990: 	    $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
                    991:                      $chparms;
                    992:         }
1.37      www       993: 
1.8       www       994: # ------------------------------------------------------- Now have all metadata
1.5       www       995: 
1.8       www       996:         $scrout.=
1.77      matthew   997:      '<form name="pubform" action="/adm/publish" method="post">'.
1.63      albertel  998:        '<p><input type="submit" value="Finalize Publication" /></p>'.
1.11      www       999:           &hiddenfield('phase','two').
                   1000:           &hiddenfield('filename',$ENV{'form.filename'}).
                   1001: 	  &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
1.58      www      1002:           &hiddenfield('dependencies',join(',',keys %allow)).
1.10      www      1003:           &textfield('Title','title',$metadatafields{'title'}).
                   1004:           &textfield('Author(s)','author',$metadatafields{'author'}).
                   1005: 	  &textfield('Subject','subject',$metadatafields{'subject'});
1.5       www      1006: 
                   1007: # --------------------------------------------------- Scan content for keywords
1.7       www      1008: 
1.84      bowersj2 1009:         my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
1.77      matthew  1010: 	my $keywordout=<<"END";
                   1011: <script>
                   1012: function checkAll(field)
                   1013: {
                   1014:     for (i = 0; i < field.length; i++)
                   1015:         field[i].checked = true ;
                   1016: }
                   1017: 
                   1018: function uncheckAll(field)
                   1019: {
                   1020:     for (i = 0; i < field.length; i++)
                   1021:         field[i].checked = false ;
                   1022: }
                   1023: </script>
1.84      bowersj2 1024: <p><b>Keywords: $keywords_help</b> 
1.77      matthew  1025: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)"> 
                   1026: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)"> 
                   1027: <br />
                   1028: END
                   1029:         $keywordout.='<table border=2><tr>';
1.7       www      1030:         my $colcount=0;
1.67      www      1031:         my %keywords=();
1.7       www      1032:         
1.52      albertel 1033: 	if (length($content)<500000) {
1.5       www      1034: 	    my $textonly=$content;
                   1035:             $textonly=~s/\<script[^\<]+\<\/script\>//g;
                   1036:             $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
                   1037:             $textonly=~s/\<[^\>]*\>//g;
                   1038:             $textonly=~tr/A-Z/a-z/;
                   1039:             $textonly=~s/[\$\&][a-z]\w*//g;
                   1040:             $textonly=~s/[^a-z\s]//g;
                   1041: 
1.65      harris41 1042:             foreach ($textonly=~m/(\w+)/g) {
1.50      www      1043: 		unless ($nokey{$_}) {
                   1044:                    $keywords{$_}=1;
                   1045:                 } 
1.65      harris41 1046:             }
1.67      www      1047:         }
1.5       www      1048: 
1.67      www      1049:             
1.65      harris41 1050:             foreach (split(/\W+/,$metadatafields{'keywords'})) {
1.12      www      1051: 		$keywords{$_}=1;
1.65      harris41 1052:             }
1.5       www      1053: 
1.65      harris41 1054:             foreach (sort keys %keywords) {
1.77      matthew  1055:                 $keywordout.='<td><input type=checkbox name="keywords" value="'.$_.'"';
1.67      www      1056:                 if ($metadatafields{'keywords'}) {
                   1057:                    if ($metadatafields{'keywords'}=~/$_/) { 
                   1058:                       $keywordout.=' checked'; 
                   1059:                    }
                   1060: 	        } elsif (&Apache::loncommon::keyword($_)) {
1.73      albertel 1061: 	            $keywordout.=' checked';
1.67      www      1062:                 } 
1.8       www      1063:                 $keywordout.='>'.$_.'</td>';
1.7       www      1064:                 if ($colcount>10) {
                   1065: 		    $keywordout.="</tr><tr>\n";
                   1066:                     $colcount=0;
                   1067:                 }
1.50      www      1068:                 $colcount++;
1.65      harris41 1069:             }
1.50      www      1070:         
1.51      www      1071: 	$keywordout.='</tr></table>';
                   1072: 
                   1073:         $scrout.=$keywordout;
1.9       www      1074: 
1.12      www      1075:         $scrout.=&textfield('Additional Keywords','addkey','');
                   1076: 
1.10      www      1077:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
1.9       www      1078: 
                   1079:         $scrout.=
                   1080:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
                   1081:               $metadatafields{'abstract'}.'</textarea>';
                   1082: 
1.11      www      1083: 	$source=~/\.(\w+)$/;
                   1084: 
                   1085: 	$scrout.=&hiddenfield('mime',$1);
                   1086: 
1.10      www      1087:         $scrout.=&selectbox('Language','language',
1.65      harris41 1088:                             $metadatafields{'language'},
1.70      harris41 1089: 			    \&Apache::loncommon::languagedescription,
1.65      harris41 1090: 			    (&Apache::loncommon::languageids),
                   1091: 			     );
1.11      www      1092: 
                   1093:         unless ($metadatafields{'creationdate'}) {
                   1094: 	    $metadatafields{'creationdate'}=time;
                   1095:         }
                   1096:         $scrout.=&hiddenfield('creationdate',$metadatafields{'creationdate'});
                   1097: 
                   1098:         $scrout.=&hiddenfield('lastrevisiondate',time);
                   1099: 
1.9       www      1100: 			   
1.10      www      1101: 	$scrout.=&textfield('Publisher/Owner','owner',
                   1102:                             $metadatafields{'owner'});
1.84      bowersj2 1103: 
1.94      harris41 1104: # -------------------------------------------------- Correct copyright for rat.
1.45      www      1105:     if ($style eq 'rat') {
1.65      harris41 1106: 	if ($metadatafields{'copyright'} eq 'public') { 
                   1107: 	    delete $metadatafields{'copyright'};
                   1108: 	}
                   1109:         $scrout.=&selectbox('Copyright/Distribution','copyright',
                   1110:                             $metadatafields{'copyright'},
1.70      harris41 1111: 			    \&Apache::loncommon::copyrightdescription,
1.65      harris41 1112: 		     (grep !/^public$/,(&Apache::loncommon::copyrightids)));
                   1113:     }
                   1114:     else {
1.10      www      1115:         $scrout.=&selectbox('Copyright/Distribution','copyright',
1.65      harris41 1116:                             $metadatafields{'copyright'},
1.70      harris41 1117: 			    \&Apache::loncommon::copyrightdescription,
1.65      harris41 1118: 			     (&Apache::loncommon::copyrightids));
                   1119:     }
1.84      bowersj2 1120: 
1.94      harris41 1121:     my $copyright_help =
                   1122:         Apache::loncommon::help_open_topic('Publishing_Copyright');
1.84      bowersj2 1123:     $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
1.8       www      1124:     return $scrout.
1.94      harris41 1125:         '<p><input type="submit" value="Finalize Publication" /></p></form>';
1.2       www      1126: }
1.1       www      1127: 
1.90      matthew  1128: #########################################
                   1129: #########################################
                   1130: 
                   1131: =pod 
                   1132: 
1.94      harris41 1133: =item B<phasetwo>
1.90      matthew  1134: 
                   1135: Render second interface showing status of publication steps.
                   1136: This is publication step two.
                   1137: 
1.94      harris41 1138: Parameters:
                   1139: 
                   1140: =over 4
                   1141: 
                   1142: =item I<$source>
                   1143: 
                   1144: =item I<$target>
                   1145: 
                   1146: =item I<$style>
                   1147: 
                   1148: =item I<$distarget>
                   1149: 
                   1150: =back
                   1151: 
                   1152: Returns:
                   1153: 
                   1154: =over 4
                   1155: 
                   1156: =item Scalar string
                   1157: 
                   1158: String contains status (errors and warnings) and information associated with
                   1159: the server's attempts at publication.
                   1160: 
1.90      matthew  1161: =cut
1.12      www      1162: 
1.90      matthew  1163: #########################################
                   1164: #########################################
1.11      www      1165: sub phasetwo {
                   1166: 
1.24      harris41 1167:     my ($source,$target,$style,$distarget)=@_;
1.11      www      1168:     my $logfile;
                   1169:     my $scrout='';
                   1170:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
                   1171: 	return 
                   1172:          '<font color=red>No write permission to user directory, FAIL</font>';
                   1173:     }
                   1174:     print $logfile 
                   1175: "\n================= Publish ".localtime()." Phase Two  ================\n";
                   1176: 
                   1177:      %metadatafields=();
                   1178:      %metadatakeys=();
                   1179: 
                   1180:      &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
                   1181: 
                   1182:      $metadatafields{'title'}=$ENV{'form.title'};
                   1183:      $metadatafields{'author'}=$ENV{'form.author'};
                   1184:      $metadatafields{'subject'}=$ENV{'form.subject'};
                   1185:      $metadatafields{'notes'}=$ENV{'form.notes'};
                   1186:      $metadatafields{'abstract'}=$ENV{'form.abstract'};
                   1187:      $metadatafields{'mime'}=$ENV{'form.mime'};
                   1188:      $metadatafields{'language'}=$ENV{'form.language'};
1.93      matthew  1189:      $metadatafields{'creationdate'}=
                   1190:          &sqltime($ENV{'form.creationdate'});
                   1191:      $metadatafields{'lastrevisiondate'}=
                   1192:          &sqltime($ENV{'form.lastrevisiondate'});
1.11      www      1193:      $metadatafields{'owner'}=$ENV{'form.owner'};
                   1194:      $metadatafields{'copyright'}=$ENV{'form.copyright'};
1.60      www      1195:      $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
1.12      www      1196: 
                   1197:      my $allkeywords=$ENV{'form.addkey'};
1.93      matthew  1198:      if (exists($ENV{'form.keywords'})) {
                   1199:          if (ref($ENV{'form.keywords'})) {
                   1200:              $allkeywords .= ','.join(',',@{$ENV{'form.keywords'}});
                   1201:          } else {
                   1202:              $allkeywords .= ','.$ENV{'form.keywords'};
1.78      matthew  1203:          }
1.65      harris41 1204:      }
1.12      www      1205:      $allkeywords=~s/\W+/\,/;
                   1206:      $allkeywords=~s/^\,//;
                   1207:      $metadatafields{'keywords'}=$allkeywords;
                   1208:  
                   1209:      {
                   1210:        print $logfile "\nWrite metadata file for ".$source;
                   1211:        my $mfh;
                   1212:        unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
                   1213: 	return 
                   1214:          '<font color=red>Could not write metadata, FAIL</font>';
1.65      harris41 1215:        }
                   1216:        foreach (sort keys %metadatafields) {
1.12      www      1217: 	 unless ($_=~/\./) {
                   1218:            my $unikey=$_;
                   1219:            $unikey=~/^([A-Za-z]+)/;
                   1220:            my $tag=$1;
                   1221:            $tag=~tr/A-Z/a-z/;
                   1222:            print $mfh "\n\<$tag";
1.65      harris41 1223:            foreach (split(/\,/,$metadatakeys{$unikey})) {
1.12      www      1224:                my $value=$metadatafields{$unikey.'.'.$_};
                   1225:                $value=~s/\"/\'\'/g;
                   1226:                print $mfh ' '.$_.'="'.$value.'"';
1.65      harris41 1227:            }
1.76      albertel 1228: 	   print $mfh '>'.
                   1229: 	     &HTML::Entities::encode($metadatafields{$unikey})
                   1230: 	       .'</'.$tag.'>';
1.12      www      1231:          }
1.65      harris41 1232:        }
1.12      www      1233:        $scrout.='<p>Wrote Metadata';
                   1234:        print $logfile "\nWrote metadata";
                   1235:      }
                   1236: 
1.24      harris41 1237: # -------------------------------- Synchronize entry with SQL metadata database
1.89      matthew  1238:     my $warning;
                   1239:     $metadatafields{'url'} = $distarget;
                   1240:     $metadatafields{'version'} = 'current';
                   1241:     unless ($metadatafields{'copyright'} eq 'priv') {
                   1242:         my ($error,$success) = &store_metadata(\%metadatafields);
1.91      matthew  1243:         if ($success) {
1.89      matthew  1244:             $scrout.='<p>Synchronized SQL metadata database';
                   1245:             print $logfile "\nSynchronized SQL metadata database";
                   1246:         } else {
                   1247:             $warning.=$error;
                   1248:             print $logfile "\n".$error;
                   1249:         }
                   1250:     } else {
                   1251:         $scrout.='<p>Private Publication - did not synchronize database';
                   1252:         print $logfile "\nPrivate: Did not synchronize data into ".
                   1253:             "SQL metadata database";
1.24      harris41 1254:     }
1.12      www      1255: # ----------------------------------------------------------- Copy old versions
                   1256:    
                   1257: if (-e $target) {
                   1258:     my $filename;
                   1259:     my $maxversion=0;
                   1260:     $target=~/(.*)\/([^\/]+)\.(\w+)$/;
                   1261:     my $srcf=$2;
                   1262:     my $srct=$3;
                   1263:     my $srcd=$1;
                   1264:     unless ($srcd=~/^\/home\/httpd\/html\/res/) {
                   1265: 	print $logfile "\nPANIC: Target dir is ".$srcd;
                   1266:         return "<font color=red>Invalid target directory, FAIL</font>";
                   1267:     }
                   1268:     opendir(DIR,$srcd);
                   1269:     while ($filename=readdir(DIR)) {
                   1270:        if ($filename=~/$srcf\.(\d+)\.$srct$/) {
                   1271: 	   $maxversion=($1>$maxversion)?$1:$maxversion;
                   1272:        }
                   1273:     }
                   1274:     closedir(DIR);
                   1275:     $maxversion++;
                   1276:     $scrout.='<p>Creating old version '.$maxversion;
                   1277:     print $logfile "\nCreating old version ".$maxversion;
                   1278: 
                   1279:     my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
                   1280: 
1.13      www      1281:         if (copy($target,$copyfile)) {
1.12      www      1282: 	    print $logfile "Copied old target to ".$copyfile."\n";
                   1283:             $scrout.='<p>Copied old target file';
                   1284:         } else {
1.13      www      1285: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
                   1286:            return "<font color=red>Failed to copy old target, $!, FAIL</font>";
1.12      www      1287:         }
                   1288: 
                   1289: # --------------------------------------------------------------- Copy Metadata
                   1290: 
                   1291: 	$copyfile=$copyfile.'.meta';
1.13      www      1292: 
                   1293:         if (copy($target.'.meta',$copyfile)) {
1.14      www      1294: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
1.12      www      1295:             $scrout.='<p>Copied old metadata';
                   1296:         } else {
1.13      www      1297: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1.14      www      1298:             if (-e $target.'.meta') {
                   1299:                return 
1.13      www      1300:        "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
1.14      www      1301: 	    }
1.12      www      1302:         }
1.11      www      1303: 
                   1304: 
1.12      www      1305: } else {
                   1306:     $scrout.='<p>Initial version';
                   1307:     print $logfile "\nInitial version";
                   1308: }
                   1309: 
                   1310: # ---------------------------------------------------------------- Write Source
                   1311: 	my $copyfile=$target;
                   1312: 
                   1313:            my @parts=split(/\//,$copyfile);
                   1314:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1315: 
                   1316:            my $count;
                   1317:            for ($count=5;$count<$#parts;$count++) {
                   1318:                $path.="/$parts[$count]";
                   1319:                if ((-e $path)!=1) {
                   1320:                    print $logfile "\nCreating directory ".$path;
                   1321:                    $scrout.='<p>Created directory '.$parts[$count];
                   1322: 		   mkdir($path,0777);
                   1323:                }
                   1324:            }
                   1325: 
1.13      www      1326:         if (copy($source,$copyfile)) {
1.12      www      1327: 	    print $logfile "Copied original source to ".$copyfile."\n";
                   1328:             $scrout.='<p>Copied source file';
                   1329:         } else {
1.13      www      1330: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
                   1331:             return "<font color=red>Failed to copy source, $!, FAIL</font>";
1.12      www      1332:         }
                   1333: 
                   1334: # --------------------------------------------------------------- Copy Metadata
                   1335: 
1.13      www      1336:         $copyfile=$copyfile.'.meta';
                   1337: 
                   1338:         if (copy($source.'.meta',$copyfile)) {
1.12      www      1339: 	    print $logfile "Copied original metadata to ".$copyfile."\n";
                   1340:             $scrout.='<p>Copied metadata';
                   1341:         } else {
1.13      www      1342: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1.12      www      1343:             return 
1.13      www      1344:           "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
1.12      www      1345:         }
                   1346: 
                   1347: # --------------------------------------------------- Send update notifications
                   1348: 
1.85      albertel 1349:     my @subscribed=&get_subscribed_hosts($target);
                   1350:     foreach my $subhost (@subscribed) {
                   1351: 	$scrout.='<p>Notifying host '.$subhost.':';
                   1352: 	print $logfile "\nNotifying host ".$subhost.':';
                   1353: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
                   1354: 	$scrout.=$reply;
                   1355: 	print $logfile $reply;
1.20      www      1356:     }
                   1357: 
                   1358: # ---------------------------------------- Send update notifications, meta only
                   1359: 
1.85      albertel 1360:     my @subscribedmeta=&get_subscribed_hosts("$target.meta");
                   1361:     foreach my $subhost (@subscribedmeta) {
                   1362: 	$scrout.='<p>Notifying host for metadata only '.$subhost.':';
                   1363: 	print $logfile "\nNotifying host for metadata only ".$subhost.':';
                   1364: 	my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
                   1365: 					    $subhost);
                   1366: 	$scrout.=$reply;
                   1367: 	print $logfile $reply;
1.12      www      1368:     }
                   1369: 
                   1370: # ------------------------------------------------ Provide link to new resource
                   1371: 
                   1372:     my $thisdistarget=$target;
                   1373:     $thisdistarget=~s/^$docroot//;
                   1374: 
1.22      www      1375:     my $thissrc=$source;
                   1376:     $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
                   1377: 
                   1378:     my $thissrcdir=$thissrc;
                   1379:     $thissrcdir=~s/\/[^\/]+$/\//;
                   1380: 
                   1381: 
1.29      harris41 1382:     return $warning.$scrout.
1.94      harris41 1383:       '<hr><a href="'.$thisdistarget.'"><font size="+2">'.
                   1384:       'View Published Version</font></a>'.
1.22      www      1385:       '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
                   1386:       '<p><a href="'.$thissrcdir.
1.94      harris41 1387:       '"><font size="+2">Back to Source Directory</font></a>';
1.22      www      1388: 
1.11      www      1389: }
                   1390: 
1.95    ! www      1391: #########################################
        !          1392: 
        !          1393: sub batchpublish {
        !          1394:     my ($r,$srcfile)=@_;
        !          1395:     my $thisdisfn=$srcfile;
        !          1396:     $thisdisfn=~s/\/home\/korte\/public_html\///;
        !          1397:     $srcfile=~s/\/+/\//g;
        !          1398:     $r->print('<h2>Publishing <tt>'.$thisdisfn.'</tt></h2>');
        !          1399: }
1.1       www      1400: 
1.90      matthew  1401: #########################################
1.95    ! www      1402: 
        !          1403: sub publishdirectory {
        !          1404:     my ($r,$fn,$thisdisfn)=@_;
        !          1405:       $r->print('<h1>Directory <tt>'.$thisdisfn.'/</tt></h1>');
        !          1406: 
        !          1407:       my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
        !          1408: 
        !          1409:       opendir(DIR,$fn);
        !          1410:       my @files=sort(readdir(DIR));
        !          1411:       foreach my $filename (@files) {
        !          1412:          my ($cdev,$cino,$cmode,$cnlink,
        !          1413:             $cuid,$cgid,$crdev,$csize,
        !          1414:             $catime,$cmtime,$cctime,
        !          1415:             $cblksize,$cblocks)=stat($fn.'/'.$filename);
        !          1416: 
        !          1417:          my $extension='';
        !          1418:          if ($filename=~/\.(\w+)$/) { $extension=$1; }
        !          1419:          if ($cmode&$dirptr) {
        !          1420: 	   if (($filename!~/^\./) && ($ENV{'form.pubrec'})) {
        !          1421: 	      &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
        !          1422: 	   }
        !          1423:          } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
        !          1424:                   ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
        !          1425:              &batchpublish($r,$fn.'/'.$filename);
        !          1426:              $r->rflush();
        !          1427:          }
        !          1428:       }
        !          1429:       closedir(DIR);
        !          1430: }
1.90      matthew  1431: #########################################
                   1432: 
                   1433: =pod
                   1434: 
1.94      harris41 1435: =item B<handler>
1.90      matthew  1436: 
                   1437: A basic outline of the handler subroutine follows.
                   1438: 
                   1439: =over 4
                   1440: 
1.94      harris41 1441: =item *
                   1442: 
                   1443: Get query string for limited number of parameters.
                   1444: 
                   1445: =item *
                   1446: 
                   1447: Check filename.
                   1448: 
                   1449: =item *
                   1450: 
                   1451: File is there and owned, init lookup tables.
                   1452: 
                   1453: =item *
1.90      matthew  1454: 
1.94      harris41 1455: Start page output.
1.90      matthew  1456: 
1.94      harris41 1457: =item *
1.90      matthew  1458: 
1.94      harris41 1459: Evaluate individual file, and then output information.
1.90      matthew  1460: 
1.94      harris41 1461: =item *
1.90      matthew  1462: 
1.94      harris41 1463: Publishing from $thisfn to $thistarget with $thisembstyle.
1.90      matthew  1464: 
                   1465: =back
                   1466: 
                   1467: =cut
                   1468: 
                   1469: #########################################
                   1470: #########################################
1.1       www      1471: sub handler {
                   1472:   my $r=shift;
1.2       www      1473: 
                   1474:   if ($r->header_only) {
                   1475:      $r->content_type('text/html');
                   1476:      $r->send_http_header;
                   1477:      return OK;
                   1478:   }
                   1479: 
1.43      www      1480: # Get query string for limited number of parameters
                   1481: 
1.80      matthew  1482:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1483:                                             ['filename']);
1.43      www      1484: 
1.2       www      1485: # -------------------------------------------------------------- Check filename
                   1486: 
                   1487:   my $fn=$ENV{'form.filename'};
                   1488: 
1.27      www      1489:   
1.2       www      1490:   unless ($fn) { 
1.27      www      1491:      $r->log_reason($cuname.' at '.$cudom.
1.2       www      1492:          ' trying to publish empty filename', $r->filename); 
                   1493:      return HTTP_NOT_FOUND;
                   1494:   } 
1.4       www      1495: 
1.31      www      1496:   ($cuname,$cudom)=
                   1497:     &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
                   1498:   unless (($cuname) && ($cudom)) {
1.27      www      1499:      $r->log_reason($cuname.' at '.$cudom.
1.4       www      1500:          ' trying to publish file '.$ENV{'form.filename'}.
1.27      www      1501:          ' ('.$fn.') - not authorized', 
                   1502:          $r->filename); 
                   1503:      return HTTP_NOT_ACCEPTABLE;
                   1504:   }
                   1505: 
                   1506:   unless (&Apache::lonnet::homeserver($cuname,$cudom) 
                   1507:           eq $r->dir_config('lonHostID')) {
                   1508:      $r->log_reason($cuname.' at '.$cudom.
                   1509:          ' trying to publish file '.$ENV{'form.filename'}.
                   1510:          ' ('.$fn.') - not homeserver ('.
                   1511:          &Apache::lonnet::homeserver($cuname,$cudom).')', 
1.4       www      1512:          $r->filename); 
                   1513:      return HTTP_NOT_ACCEPTABLE;
                   1514:   }
1.2       www      1515: 
1.43      www      1516:   $fn=~s/^http\:\/\/[^\/]+//;
                   1517:   $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
1.2       www      1518: 
                   1519:   my $targetdir='';
1.12      www      1520:   $docroot=$r->dir_config('lonDocRoot'); 
1.27      www      1521:   if ($1 ne $cuname) {
                   1522:      $r->log_reason($cuname.' at '.$cudom.
1.2       www      1523:          ' trying to publish unowned file '.$ENV{'form.filename'}.
                   1524:          ' ('.$fn.')', 
                   1525:          $r->filename); 
                   1526:      return HTTP_NOT_ACCEPTABLE;
                   1527:   } else {
1.27      www      1528:       $targetdir=$docroot.'/res/'.$cudom;
1.2       www      1529:   }
                   1530:                                  
                   1531:   
                   1532:   unless (-e $fn) { 
1.27      www      1533:      $r->log_reason($cuname.' at '.$cudom.
1.2       www      1534:          ' trying to publish non-existing file '.$ENV{'form.filename'}.
                   1535:          ' ('.$fn.')', 
                   1536:          $r->filename); 
                   1537:      return HTTP_NOT_FOUND;
                   1538:   } 
                   1539: 
1.11      www      1540: unless ($ENV{'form.phase'} eq 'two') {
                   1541: 
1.94      harris41 1542: # -------------------------------- File is there and owned, init lookup tables.
1.2       www      1543: 
1.3       www      1544:   %addid=();
                   1545: 
                   1546:   {
                   1547:       my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
                   1548:       while (<$fh>=~/(\w+)\s+(\w+)/) {
                   1549:           $addid{$1}=$2;
                   1550:       }
1.5       www      1551:   }
                   1552: 
                   1553:   %nokey=();
                   1554: 
                   1555:   {
                   1556:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
1.65      harris41 1557:       while (<$fh>) {
1.5       www      1558:           my $word=$_;
                   1559:           chomp($word);
                   1560:           $nokey{$word}=1;
1.65      harris41 1561:       }
1.3       www      1562:   }
1.11      www      1563: 
                   1564: }
                   1565: 
1.94      harris41 1566: # ---------------------------------------------------------- Start page output.
1.2       www      1567: 
1.1       www      1568:   $r->content_type('text/html');
                   1569:   $r->send_http_header;
                   1570: 
                   1571:   $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
1.95    ! www      1572:   $r->print(&Apache::loncommon::bodytag('Resource Publication'));
1.2       www      1573:   my $thisfn=$fn;
1.95    ! www      1574: 
        !          1575:   my $thistarget=$thisfn;
        !          1576:       
        !          1577:   $thistarget=~s/^\/home/$targetdir/;
        !          1578:   $thistarget=~s/\/public\_html//;
        !          1579: 
        !          1580:   my $thisdistarget=$thistarget;
        !          1581:   $thisdistarget=~s/^$docroot//;
        !          1582: 
        !          1583:   my $thisdisfn=$thisfn;
        !          1584:   $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
        !          1585: 
        !          1586:   if ($fn=~/\/$/) {
        !          1587: # -------------------------------------------------------- This is a directory
        !          1588:       &publishdirectory($r,$fn,$thisdisfn);
        !          1589: 
        !          1590:   } else {
1.94      harris41 1591: # ---------------------- Evaluate individual file, and then output information.
1.2       www      1592:       $thisfn=~/\.(\w+)$/;
                   1593:       my $thistype=$1;
1.65      harris41 1594:       my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1.2       www      1595: 
                   1596:       $r->print('<h2>Publishing '.
1.66      harris41 1597:         &Apache::loncommon::filedescription($thistype).' <tt>'.
1.95    ! www      1598:         '<a href="/~'.$cuname.'/'.$thisdisfn.'" target="cat">'.$thisdisfn.
        !          1599:         '</a></tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
1.27      www      1600:    
1.94      harris41 1601:       if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
                   1602:           $r->print('<h3><font color="red">Co-Author: '.$cuname.' at '.$cudom.
                   1603: 		    '</font></h3>');
1.27      www      1604:       }
1.26      www      1605: 
1.65      harris41 1606:       if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
1.94      harris41 1607:           $r->print('<br /><a href="/adm/diff?filename=/~'.$cuname.'/'.
1.28      www      1608:                     $thisdisfn.
1.94      harris41 1609:   	  '&versionone=priv" target="cat">Diffs with Current Version</a><p>');
1.26      www      1610:       }
1.11      www      1611:   
1.94      harris41 1612: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
1.2       www      1613: 
1.11      www      1614:        unless ($ENV{'form.phase'} eq 'two') {
1.27      www      1615:          $r->print(
1.94      harris41 1616:           '<hr />'.&publish($thisfn,$thistarget,$thisembstyle));
1.11      www      1617:        } else {
1.27      www      1618:          $r->print(
1.94      harris41 1619:           '<hr />'.&phasetwo($thisfn,$thistarget,
                   1620: 			     $thisembstyle,$thisdistarget)); 
1.11      www      1621:        }  
1.2       www      1622: 
1.11      www      1623:   }
1.1       www      1624:   $r->print('</body></html>');
1.15      www      1625: 
1.1       www      1626:   return OK;
                   1627: }
                   1628: 
                   1629: 1;
                   1630: __END__
                   1631: 
1.89      matthew  1632: =pod
1.66      harris41 1633: 
                   1634: =back
                   1635: 
1.89      matthew  1636: =cut
1.66      harris41 1637: 

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