File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.58: download - view: text, annotated - select for diffs
Wed Dec 5 20:37:06 2001 UTC (22 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Check dependencies

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.58 2001/12/05 20:37:06 www Exp $
    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: #
   28: # 
   29: # (TeX Content Handler
   30: #
   31: # 05/29/00,05/30,10/11 Gerd Kortemeyer)
   32: #
   33: # 11/28,11/29,11/30,12/01,12/02,12/04,12/23 Gerd Kortemeyer
   34: # 03/23 Guy Albertelli
   35: # 03/24,03/29,04/03 Gerd Kortemeyer
   36: # 04/16/2001 Scott Harrison
   37: # 05/03,05/05,05/07 Gerd Kortemeyer
   38: # 05/28/2001 Scott Harrison
   39: # 06/23,08/07,08/11,8/13,8/17,8/18,8/24,9/26,10/16 Gerd Kortemeyer
   40: # 12/04,12/05 Guy Albertelli
   41: # 12/05 Gerd Kortemeyer
   42: 
   43: package Apache::lonpublisher;
   44: 
   45: use strict;
   46: use Apache::File;
   47: use File::Copy;
   48: use Apache::Constants qw(:common :http :methods);
   49: use HTML::TokeParser;
   50: use Apache::lonxml;
   51: use Apache::lonhomework;
   52: use Apache::loncacc;
   53: use DBI;
   54: 
   55: my %addid;
   56: my %nokey;
   57: my %language;
   58: my %cprtag;
   59: 
   60: my %metadatafields;
   61: my %metadatakeys;
   62: 
   63: my $docroot;
   64: 
   65: my $cuname;
   66: my $cudom;
   67: 
   68: # ----------------------------------------------- Evaluate string with metadata
   69: 
   70: sub metaeval {
   71:     my $metastring=shift;
   72:    
   73:         my $parser=HTML::TokeParser->new(\$metastring);
   74:         my $token;
   75:         while ($token=$parser->get_token) {
   76:            if ($token->[0] eq 'S') {
   77: 	      my $entry=$token->[1];
   78:               my $unikey=$entry;
   79:               if (defined($token->[2]->{'package'})) { 
   80:                   $unikey.='_package_'.$token->[2]->{'package'};
   81:               } 
   82:               if (defined($token->[2]->{'part'})) { 
   83:                  $unikey.='_'.$token->[2]->{'part'}; 
   84: 	      }
   85:               if (defined($token->[2]->{'id'})) { 
   86:                   $unikey.='_'.$token->[2]->{'id'};
   87:               } 
   88:               if (defined($token->[2]->{'name'})) { 
   89:                  $unikey.='_'.$token->[2]->{'name'}; 
   90: 	      }
   91:                map {
   92: 		  $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
   93:                   if ($metadatakeys{$unikey}) {
   94: 		      $metadatakeys{$unikey}.=','.$_;
   95:                   } else {
   96:                       $metadatakeys{$unikey}=$_;
   97:                   }
   98:               } @{$token->[3]};
   99:               if ($metadatafields{$unikey}) {
  100: 		  my $newentry=$parser->get_text('/'.$entry);
  101:                   unless (($metadatafields{$unikey}=~/$newentry/) ||
  102:                           ($newentry eq '')) {
  103:                      $metadatafields{$unikey}.=', '.$newentry;
  104: 		  }
  105: 	      } else {
  106:                  $metadatafields{$unikey}=$parser->get_text('/'.$entry);
  107:               }
  108:           }
  109:        }
  110: }
  111: 
  112: # -------------------------------------------------------- Read a metadata file
  113: 
  114: sub metaread {
  115:     my ($logfile,$fn)=@_;
  116:     unless (-e $fn) {
  117: 	print $logfile 'No file '.$fn."\n";
  118:         return '<br><b>No file:</b> <tt>'.$fn.'</tt>';
  119:     }
  120:     print $logfile 'Processing '.$fn."\n";
  121:     my $metastring;
  122:     {
  123:      my $metafh=Apache::File->new($fn);
  124:      $metastring=join('',<$metafh>);
  125:     }
  126:     &metaeval($metastring);
  127:     return '<br><b>Processed file:</b> <tt>'.$fn.'</tt>';
  128: }
  129: 
  130: # ---------------------------- convert 'time' format into a datetime sql format
  131: sub sqltime {
  132:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  133: 	localtime(@_[0]);
  134:     $mon++; $year+=1900;
  135:     return "$year-$mon-$mday $hour:$min:$sec";
  136: }
  137: 
  138: # --------------------------------------------------------- Various form fields
  139: 
  140: sub textfield {
  141:     my ($title,$name,$value)=@_;
  142:     return "\n<p><b>$title:</b><br>".
  143:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
  144: }
  145: 
  146: sub hiddenfield {
  147:     my ($name,$value)=@_;
  148:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
  149: }
  150: 
  151: sub selectbox {
  152:     my ($title,$name,$value,%options)=@_;
  153:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
  154:     map {
  155:         $selout.='<option value="'.$_.'"';
  156:         if ($_ eq $value) { $selout.=' selected'; }
  157:         $selout.='>'.$options{$_}.'</option>';
  158:     } sort keys %options;
  159:     return $selout.'</select>';
  160: }
  161: 
  162: # -------------------------------------------------------- Publication Step One
  163: 
  164: sub urlfixup {
  165:     my ($url,$target)=@_;
  166:     unless ($url) { return ''; }
  167:     my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
  168:     map {
  169: 	if ($_ eq $host) {
  170: 	    $url=~s/^http\:\/\///;
  171:             $url=~s/^$host//;
  172:         }
  173:     } values %Apache::lonnet::hostname;
  174:     if ($url=~/^http\:\/\//) { return $url; }
  175:     $url=~s/\~$cuname/res\/$cudom\/$cuname/;
  176:     if ($target) {
  177: 	$target=~s/\/[^\/]+$//;
  178:        $url=&Apache::lonnet::hreflocation($target,$url);
  179:     }
  180:     return $url;
  181: }
  182: 
  183: sub publish {
  184: 
  185:     my ($source,$target,$style)=@_;
  186:     my $logfile;
  187:     my $scrout='';
  188:     my $allmeta='';
  189:     my $content='';
  190:     my %allow=();
  191:     undef %allow;
  192: 
  193:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  194: 	return 
  195:          '<font color=red>No write permission to user directory, FAIL</font>';
  196:     }
  197:     print $logfile 
  198: "\n\n================= Publish ".localtime()." Phase One  ================\n";
  199: 
  200:     if (($style eq 'ssi') || ($style eq 'rat')) {
  201: # ------------------------------------------------------- This needs processing
  202: 
  203: # ----------------------------------------------------------------- Backup Copy
  204: 	my $copyfile=$source.'.save';
  205:         if (copy($source,$copyfile)) {
  206: 	    print $logfile "Copied original file to ".$copyfile."\n";
  207:         } else {
  208: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
  209:           return "<font color=red>Failed to write backup copy, $!,FAIL</font>";
  210:         }
  211: # ------------------------------------------------------------- IDs and indices
  212: 
  213:         my $maxindex=10;
  214:         my $maxid=10;
  215: 
  216:         my $needsfixup=0;
  217: 
  218:         {
  219:           my $org=Apache::File->new($source);
  220:           $content=join('',<$org>);
  221:         }
  222:         {
  223:           my $parser=HTML::TokeParser->new(\$content);
  224:           my $token;
  225:           while ($token=$parser->get_token) {
  226:               if ($token->[0] eq 'S') {
  227:                   my $counter;
  228: 		  if ($counter=$addid{$token->[1]}) {
  229: 		      if ($counter eq 'id') {
  230: 			  if (defined($token->[2]->{'id'})) {
  231:                              $maxid=
  232: 		       ($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
  233: 			 } else {
  234:                              $needsfixup=1;
  235:                          }
  236:                       } else {
  237:  			  if (defined($token->[2]->{'index'})) {
  238:                              $maxindex=
  239: 	   ($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
  240: 			  } else {
  241:                              $needsfixup=1;
  242: 			  }
  243: 		      }
  244: 		  }
  245:               }
  246:           }
  247:       }
  248:       if ($needsfixup) {
  249:           print $logfile "Needs ID and/or index fixup\n".
  250: 	        "Max ID   : $maxid (min 10)\n".
  251:                 "Max Index: $maxindex (min 10)\n";
  252:       }
  253:           my $outstring='';
  254:           my $parser=HTML::TokeParser->new(\$content);
  255:           $parser->xml_mode(1);
  256:           my $token;
  257:           while ($token=$parser->get_token) {
  258:               if ($token->[0] eq 'S') {
  259:                 my $counter;
  260:                 my $tag=$token->[1];
  261:                 my $lctag=lc($tag);
  262:                 unless ($lctag eq 'allow') {  
  263:                   my %parms=%{$token->[2]};
  264:                   $counter=$addid{$tag};
  265:                   if (!$counter) { $counter=$addid{$lctag}; }
  266:                   if ($counter) {
  267: 		      if ($counter eq 'id') {
  268: 			  unless (defined($parms{'id'})) {
  269:                               $maxid++;
  270:                               $parms{'id'}=$maxid;
  271:                               print $logfile 'ID: '.$tag.':'.$maxid."\n";
  272:                           }
  273:                       } elsif ($counter eq 'index') {
  274:  			  unless (defined($parms{'index'})) {
  275:                               $maxindex++;
  276:                               $parms{'index'}=$maxindex;
  277:                               print $logfile 'Index: '.$tag.':'.$maxindex."\n";
  278: 			  }
  279: 		      }
  280: 		  } 
  281:                   
  282:                   map {
  283:                       if (defined($parms{$_})) {
  284: 			  my $oldurl=$parms{$_};
  285:                           my $newurl=&urlfixup($oldurl,$target);
  286:                           if ($newurl ne $oldurl) {
  287: 			      $parms{$_}=$newurl;
  288:                               print $logfile 'URL: '.$tag.':'.$oldurl.' - '.
  289: 				  $newurl."\n";
  290: 			  }
  291:                           $allow{$newurl}=1;
  292:                       }
  293:                   } ('src','href','background');
  294: 
  295:                   if ($lctag eq 'applet') {
  296: 		      my $codebase='';
  297:                       if (defined($parms{'codebase'})) {
  298: 		         my $oldcodebase=$parms{'codebase'};
  299:                          unless ($oldcodebase=~/\/$/) {
  300:                             $oldcodebase.='/';
  301:                          }
  302:                          $codebase=&urlfixup($oldcodebase,$target);
  303:                          $codebase=~s/\/$//;    
  304:                          if ($codebase ne $oldcodebase) {
  305: 			     $parms{'codebase'}=$codebase;
  306:                              print $logfile 'URL codebase: '.$tag.':'.
  307:                                   $oldcodebase.' - '.
  308: 				  $codebase."\n";
  309: 			 }
  310:                          $allow{$codebase.'/*'}=1;
  311: 		      } else {
  312:                         map {
  313:                           if (defined($parms{$_})) {
  314: 			      my $oldurl=$parms{$_};
  315:                               my $newurl=&urlfixup($oldurl,$target);
  316: 			      $newurl=~s/\/[^\/]+$/\/\*/;
  317:                                   print $logfile 'Allow: applet '.$_.':'.
  318:                                   $oldurl.' allows '.
  319: 				  $newurl."\n";
  320:                               $allow{$newurl}=1;
  321:                           }
  322:                         } ('archive','code','object');
  323:                       }
  324:                   }
  325: 
  326:                   my $newparmstring='';
  327:                   my $endtag='';
  328:                   map {
  329:                     if ($_ eq '/') {
  330:                       $endtag=' /';
  331:                     } else { 
  332:                       my $quote=($parms{$_}=~/\"/?"'":'"');
  333:                       $newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
  334: 		    }
  335:                   } keys %parms;
  336: 		  if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  337: 		  $outstring.='<'.$tag.$newparmstring.$endtag.'>';
  338: 	         } else {
  339: 		   $allow{$token->[2]->{'src'}}=1;
  340: 		 }
  341:               } elsif ($token->[0] eq 'E') {
  342: 		if ($token->[2]) {
  343:                   unless ($token->[1] eq 'allow') {
  344:                      $outstring.='</'.$token->[1].'>';
  345: 		  }
  346: 		}
  347:               } else {
  348:                   $outstring.=$token->[1];
  349:               }
  350:           }
  351: # ------------------------------------------------------------ Construct Allows
  352:      unless ($style eq 'rat') {
  353: 	$scrout.='<h3>Dependencies</h3>';
  354: 	my $allowstr="\n";
  355:         map {
  356:            $allowstr.='<allow src="'.$_.'" />'."\n";
  357:            $scrout.='<br>';
  358:            unless ($_=~/\*/) {
  359: 	       $scrout.='<a href="'.$_.'">';
  360:            }
  361:            $scrout.='<tt>'.$_.'</tt>';
  362:            unless ($_=~/\*/) {
  363: 	       $scrout.='</a>';
  364:                if (&Apache::lonnet::getfile(
  365:                    $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
  366:                                             $_.'.meta') eq '-1') {
  367: 		   $scrout.=
  368:                            ' - <font color=red>Currently not available</font>';
  369:                }
  370:            }
  371:         } keys %allow;
  372:         $outstring=~s/(\<\/[^\>]+\>\s*)$/$allowstr$1/s;
  373:     }
  374: # ------------------------------------------------------------- Write modified
  375: 
  376:         {
  377:           my $org;
  378:           unless ($org=Apache::File->new('>'.$source)) {
  379:              print $logfile "No write permit to $source\n";
  380:              return 
  381:               "<font color=red>No write permission to $source, FAIL</font>";
  382: 	  }
  383:           print $org $outstring;
  384:         }
  385: 	  $content=$outstring;
  386: 
  387:       if ($needsfixup) {
  388:           print $logfile "End of ID and/or index fixup\n".
  389: 	        "Max ID   : $maxid (min 10)\n".
  390:                 "Max Index: $maxindex (min 10)\n";
  391:       } else {
  392: 	  print $logfile "Does not need ID and/or index fixup\n";
  393:       }
  394:     }
  395: # --------------------------------------------- Initial step done, now metadata
  396: 
  397: # ---------------------------------------- Storage for metadata keys and fields
  398: 
  399:      %metadatafields=();
  400:      %metadatakeys=();
  401:      
  402:      my %oldparmstores=();
  403:      
  404:      $scrout.='<h3>Metadata Information</h3>';
  405: 
  406: # ------------------------------------------------ First, check out environment
  407:      unless (-e $source.'.meta') {
  408:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
  409: 	                          $ENV{'environment.middlename'}.' '.
  410: 		                  $ENV{'environment.lastname'}.' '.
  411: 		                  $ENV{'environment.generation'};
  412:         $metadatafields{'author'}=~s/\s+/ /g;
  413:         $metadatafields{'author'}=~s/\s+$//;
  414:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
  415: 
  416: # ------------------------------------------------ Check out directory hierachy
  417: 
  418:         my $thisdisfn=$source;
  419:         $thisdisfn=~s/^\/home\/$cuname\///;
  420: 
  421:         my @urlparts=split(/\//,$thisdisfn);
  422:         $#urlparts--;
  423: 
  424:         my $currentpath='/home/'.$cuname.'/';
  425: 
  426:         map {
  427: 	    $currentpath.=$_.'/';
  428:             $scrout.=&metaread($logfile,$currentpath.'default.meta');
  429:         } @urlparts;
  430: 
  431: # ------------------- Clear out parameters and stores (there should not be any)
  432: 
  433:         map {
  434: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  435: 		delete $metadatafields{$_};
  436:             }
  437:         } keys %metadatafields;
  438: 
  439:     } else {
  440: # ---------------------- Read previous metafile, remember parameters and stores
  441: 
  442:         $scrout.=&metaread($logfile,$source.'.meta');
  443: 
  444:         map {
  445: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  446:                 $oldparmstores{$_}=1;
  447: 		delete $metadatafields{$_};
  448:             }
  449:         } keys %metadatafields;
  450:         
  451:     }
  452: 
  453: # -------------------------------------------------- Parse content for metadata
  454:     if ($style eq 'ssi') {
  455:         my $oldenv=$ENV{'request.uri'};
  456: 
  457:         $ENV{'request.uri'}=$target;
  458:         $allmeta=Apache::lonxml::xmlparse('meta',$content);
  459:         $ENV{'request.uri'}=$oldenv;
  460: 
  461:         &metaeval($allmeta);
  462:     }
  463: # ---------------- Find and document discrepancies in the parameters and stores
  464: 
  465:         my $chparms='';
  466:         map {
  467: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  468:                 unless ($_=~/\.\w+$/) { 
  469:                    unless ($oldparmstores{$_}) {
  470: 		      print $logfile 'New: '.$_."\n";
  471:                       $chparms.=$_.' ';
  472:                    }
  473: 	        }
  474:             }
  475:         } sort keys %metadatafields;
  476:         if ($chparms) {
  477: 	    $scrout.='<p><b>New parameters or stored values:</b> '.
  478:                      $chparms;
  479:         }
  480: 
  481:         my $chparms='';
  482:         map {
  483: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  484:                 unless (($metadatafields{$_.'.name'}) ||
  485:                         ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
  486: 		    print $logfile 'Obsolete: '.$_."\n";
  487:                     $chparms.=$_.' ';
  488:                 }
  489:             }
  490:         } sort keys %oldparmstores;
  491:         if ($chparms) {
  492: 	    $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
  493:                      $chparms;
  494:         }
  495: 
  496: # ------------------------------------------------------- Now have all metadata
  497: 
  498:         $scrout.=
  499:      '<form action="/adm/publish" method="post">'.
  500:           &hiddenfield('phase','two').
  501:           &hiddenfield('filename',$ENV{'form.filename'}).
  502: 	  &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
  503:           &hiddenfield('dependencies',join(',',keys %allow)).
  504:           &textfield('Title','title',$metadatafields{'title'}).
  505:           &textfield('Author(s)','author',$metadatafields{'author'}).
  506: 	  &textfield('Subject','subject',$metadatafields{'subject'});
  507: 
  508: # --------------------------------------------------- Scan content for keywords
  509: 
  510: 	my $keywordout='<p><b>Keywords:</b><br><table border=2><tr>';
  511:         my $colcount=0;
  512:         
  513: 	if (length($content)<500000) {
  514: 	    my $textonly=$content;
  515:             $textonly=~s/\<script[^\<]+\<\/script\>//g;
  516:             $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
  517:             $textonly=~s/\<[^\>]*\>//g;
  518:             $textonly=~tr/A-Z/a-z/;
  519:             $textonly=~s/[\$\&][a-z]\w*//g;
  520:             $textonly=~s/[^a-z\s]//g;
  521: 
  522:             my %keywords=();
  523:             map {
  524: 		unless ($nokey{$_}) {
  525:                    $keywords{$_}=1;
  526:                 } 
  527:             } ($textonly=~m/(\w+)/g);
  528: 
  529:             map {
  530: 		$keywords{$_}=1;
  531:             } split(/\W+/,$metadatafields{'keywords'});
  532: 
  533:             map {
  534:                 $keywordout.='<td><input type=checkbox name="key.'.$_.'"';
  535:                 if ($metadatafields{'keywords'}=~/$_/) { 
  536:                    $keywordout.=' checked'; 
  537:                 }
  538:                 $keywordout.='>'.$_.'</td>';
  539:                 if ($colcount>10) {
  540: 		    $keywordout.="</tr><tr>\n";
  541:                     $colcount=0;
  542:                 }
  543:                 $colcount++;
  544:             } sort keys %keywords;
  545: 
  546:         } else {
  547: 	    $keywordout.='<td>File too long for keyword analysis</td>';
  548:         }         
  549:         
  550: 	$keywordout.='</tr></table>';
  551: 
  552:         $scrout.=$keywordout;
  553: 
  554:         $scrout.=&textfield('Additional Keywords','addkey','');
  555: 
  556:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
  557: 
  558:         $scrout.=
  559:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
  560:               $metadatafields{'abstract'}.'</textarea>';
  561: 
  562: 	$source=~/\.(\w+)$/;
  563: 
  564: 	$scrout.=&hiddenfield('mime',$1);
  565: 
  566:         $scrout.=&selectbox('Language','language',
  567:                             $metadatafields{'language'},%language);
  568: 
  569:         unless ($metadatafields{'creationdate'}) {
  570: 	    $metadatafields{'creationdate'}=time;
  571:         }
  572:         $scrout.=&hiddenfield('creationdate',$metadatafields{'creationdate'});
  573: 
  574:         $scrout.=&hiddenfield('lastrevisiondate',time);
  575: 
  576: 			   
  577: 	$scrout.=&textfield('Publisher/Owner','owner',
  578:                             $metadatafields{'owner'});
  579: # --------------------------------------------------- Correct copyright for rat        
  580:     if ($style eq 'rat') {
  581:        if ($metadatafields{'copyright'} eq 'public') { 
  582:           delete $metadatafields{'copyright'};
  583:        }
  584:        delete $cprtag{'public'};
  585:    }
  586: 
  587:         $scrout.=&selectbox('Copyright/Distribution','copyright',
  588:                             $metadatafields{'copyright'},%cprtag);
  589: 
  590:     return $scrout.
  591:       '<p><input type="submit" value="Finalize Publication"></form>';
  592: }
  593: 
  594: # -------------------------------------------------------- Publication Step Two
  595: 
  596: sub phasetwo {
  597: 
  598:     my ($source,$target,$style,$distarget)=@_;
  599:     my $logfile;
  600:     my $scrout='';
  601: 
  602:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  603: 	return 
  604:          '<font color=red>No write permission to user directory, FAIL</font>';
  605:     }
  606:     print $logfile 
  607: "\n================= Publish ".localtime()." Phase Two  ================\n";
  608: 
  609:      %metadatafields=();
  610:      %metadatakeys=();
  611: 
  612:      &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
  613: 
  614:      $metadatafields{'title'}=$ENV{'form.title'};
  615:      $metadatafields{'author'}=$ENV{'form.author'};
  616:      $metadatafields{'subject'}=$ENV{'form.subject'};
  617:      $metadatafields{'notes'}=$ENV{'form.notes'};
  618:      $metadatafields{'abstract'}=$ENV{'form.abstract'};
  619:      $metadatafields{'mime'}=$ENV{'form.mime'};
  620:      $metadatafields{'language'}=$ENV{'form.language'};
  621:      $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
  622:      $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
  623:      $metadatafields{'owner'}=$ENV{'form.owner'};
  624:      $metadatafields{'copyright'}=$ENV{'form.copyright'};
  625: 
  626:      my $allkeywords=$ENV{'form.addkey'};
  627:      map {
  628:          if ($_=~/^form\.key\.(\w+)/) {
  629: 	     $allkeywords.=','.$1;
  630:          }
  631:      } keys %ENV;
  632:      $allkeywords=~s/\W+/\,/;
  633:      $allkeywords=~s/^\,//;
  634:      $metadatafields{'keywords'}=$allkeywords;
  635:  
  636:      {
  637:        print $logfile "\nWrite metadata file for ".$source;
  638:        my $mfh;
  639:        unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
  640: 	return 
  641:          '<font color=red>Could not write metadata, FAIL</font>';
  642:        }    
  643:        map {
  644: 	 unless ($_=~/\./) {
  645:            my $unikey=$_;
  646:            $unikey=~/^([A-Za-z]+)/;
  647:            my $tag=$1;
  648:            $tag=~tr/A-Z/a-z/;
  649:            print $mfh "\n\<$tag";
  650:            map {
  651:                my $value=$metadatafields{$unikey.'.'.$_};
  652:                $value=~s/\"/\'\'/g;
  653:                print $mfh ' '.$_.'="'.$value.'"';
  654:            } split(/\,/,$metadatakeys{$unikey});
  655: 	   print $mfh '>'.$metadatafields{$unikey}.'</'.$tag.'>';
  656:          }
  657:        } sort keys %metadatafields;
  658:        $scrout.='<p>Wrote Metadata';
  659:        print $logfile "\nWrote metadata";
  660:      }
  661: 
  662: # -------------------------------- Synchronize entry with SQL metadata database
  663:     my %perlvar;
  664:     open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
  665:     my $configline;
  666:     while ($configline=<CONFIG>) {
  667: 	if ($configline =~ /PerlSetVar/) {
  668: 	    my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
  669: 	    chomp($varvalue);
  670: 	    $perlvar{$varname}=$varvalue;
  671: 	}
  672:     }
  673:     close(CONFIG);
  674: 
  675:     my $warning;
  676:     my $dbh;
  677:     {
  678: 	unless (
  679: 		$dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  680: 		) { 
  681: 	    $warning='<font color=red>WARNING: Cannot connect to '.
  682: 		'database!</font>';
  683: 	}
  684: 	else {
  685: 	    my %sqldatafields;
  686: 	    $sqldatafields{'url'}=$distarget;
  687: 	    my $sth=$dbh->prepare(
  688: 				  'delete from metadata where url like binary'.
  689: 				  '"'.$sqldatafields{'url'}.'"');
  690: 	    $sth->execute();
  691: 	    map {my $field=$metadatafields{$_}; $field=~s/\"/\'\'/g; 
  692: 		 $sqldatafields{$_}=$field;}
  693: 	    ('title','author','subject','keywords','notes','abstract',
  694: 	     'mime','language','creationdate','lastrevisiondate','owner',
  695: 	     'copyright');
  696: 	    
  697: 	    $sth=$dbh->prepare('insert into metadata values ('.
  698: 			       '"'.delete($sqldatafields{'title'}).'"'.','.
  699: 			       '"'.delete($sqldatafields{'author'}).'"'.','.
  700: 			       '"'.delete($sqldatafields{'subject'}).'"'.','.
  701: 			       '"'.delete($sqldatafields{'url'}).'"'.','.
  702: 			       '"'.delete($sqldatafields{'keywords'}).'"'.','.
  703: 			       '"'.'current'.'"'.','.
  704: 			       '"'.delete($sqldatafields{'notes'}).'"'.','.
  705: 			       '"'.delete($sqldatafields{'abstract'}).'"'.','.
  706: 			       '"'.delete($sqldatafields{'mime'}).'"'.','.
  707: 			       '"'.delete($sqldatafields{'language'}).'"'.','.
  708: 			       '"'.
  709: 			       sqltime(delete($sqldatafields{'creationdate'}))
  710: 			       .'"'.','.
  711: 			       '"'.
  712: 			       sqltime(delete(
  713: 			       $sqldatafields{'lastrevisiondate'})).'"'.','.
  714: 			       '"'.delete($sqldatafields{'owner'}).'"'.','.
  715: 			       '"'.delete(
  716: 			       $sqldatafields{'copyright'}).'"'.')');
  717: 	    $sth->execute();
  718: 	    $dbh->disconnect;
  719: 	    $scrout.='<p>Synchronized SQL metadata database';
  720: 	    print $logfile "\nSynchronized SQL metadata database";
  721: 	}
  722:     }
  723: 
  724: 
  725: # ----------------------------------------------------------- Copy old versions
  726:    
  727: if (-e $target) {
  728:     my $filename;
  729:     my $maxversion=0;
  730:     $target=~/(.*)\/([^\/]+)\.(\w+)$/;
  731:     my $srcf=$2;
  732:     my $srct=$3;
  733:     my $srcd=$1;
  734:     unless ($srcd=~/^\/home\/httpd\/html\/res/) {
  735: 	print $logfile "\nPANIC: Target dir is ".$srcd;
  736:         return "<font color=red>Invalid target directory, FAIL</font>";
  737:     }
  738:     opendir(DIR,$srcd);
  739:     while ($filename=readdir(DIR)) {
  740:        if ($filename=~/$srcf\.(\d+)\.$srct$/) {
  741: 	   $maxversion=($1>$maxversion)?$1:$maxversion;
  742:        }
  743:     }
  744:     closedir(DIR);
  745:     $maxversion++;
  746:     $scrout.='<p>Creating old version '.$maxversion;
  747:     print $logfile "\nCreating old version ".$maxversion;
  748: 
  749:     my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
  750: 
  751:         if (copy($target,$copyfile)) {
  752: 	    print $logfile "Copied old target to ".$copyfile."\n";
  753:             $scrout.='<p>Copied old target file';
  754:         } else {
  755: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
  756:            return "<font color=red>Failed to copy old target, $!, FAIL</font>";
  757:         }
  758: 
  759: # --------------------------------------------------------------- Copy Metadata
  760: 
  761: 	$copyfile=$copyfile.'.meta';
  762: 
  763:         if (copy($target.'.meta',$copyfile)) {
  764: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
  765:             $scrout.='<p>Copied old metadata';
  766:         } else {
  767: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
  768:             if (-e $target.'.meta') {
  769:                return 
  770:        "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
  771: 	    }
  772:         }
  773: 
  774: 
  775: } else {
  776:     $scrout.='<p>Initial version';
  777:     print $logfile "\nInitial version";
  778: }
  779: 
  780: # ---------------------------------------------------------------- Write Source
  781: 	my $copyfile=$target;
  782: 
  783:            my @parts=split(/\//,$copyfile);
  784:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  785: 
  786:            my $count;
  787:            for ($count=5;$count<$#parts;$count++) {
  788:                $path.="/$parts[$count]";
  789:                if ((-e $path)!=1) {
  790:                    print $logfile "\nCreating directory ".$path;
  791:                    $scrout.='<p>Created directory '.$parts[$count];
  792: 		   mkdir($path,0777);
  793:                }
  794:            }
  795: 
  796:         if (copy($source,$copyfile)) {
  797: 	    print $logfile "Copied original source to ".$copyfile."\n";
  798:             $scrout.='<p>Copied source file';
  799:         } else {
  800: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
  801:             return "<font color=red>Failed to copy source, $!, FAIL</font>";
  802:         }
  803: 
  804: # --------------------------------------------------------------- Copy Metadata
  805: 
  806:         $copyfile=$copyfile.'.meta';
  807: 
  808:         if (copy($source.'.meta',$copyfile)) {
  809: 	    print $logfile "Copied original metadata to ".$copyfile."\n";
  810:             $scrout.='<p>Copied metadata';
  811:         } else {
  812: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
  813:             return 
  814:           "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
  815:         }
  816: 
  817: # --------------------------------------------------- Send update notifications
  818: 
  819: {
  820: 
  821:     my $filename;
  822:  
  823:     $target=~/(.*)\/([^\/]+)$/;
  824:     my $srcf=$2;
  825:     opendir(DIR,$1);
  826:     while ($filename=readdir(DIR)) {
  827:        if ($filename=~/$srcf\.(\w+)$/) {
  828: 	   my $subhost=$1;
  829:            if ($subhost ne 'meta') {
  830: 	       $scrout.='<p>Notifying host '.$subhost.':';
  831:                print $logfile "\nNotifying host '.$subhost.':'";
  832:                my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
  833:                $scrout.=$reply;
  834:                print $logfile $reply;              
  835:            }
  836:        }
  837:     }
  838:     closedir(DIR);
  839: 
  840: }
  841: 
  842: # ---------------------------------------- Send update notifications, meta only
  843: 
  844: {
  845: 
  846:     my $filename;
  847:  
  848:     $target=~/(.*)\/([^\/]+)$/;
  849:     my $srcf=$2.'.meta';
  850:     opendir(DIR,$1);
  851:     while ($filename=readdir(DIR)) {
  852:        if ($filename=~/$srcf\.(\w+)$/) {
  853: 	   my $subhost=$1;
  854:            if ($subhost ne 'meta') {
  855: 	       $scrout.=
  856:                 '<p>Notifying host for metadata only '.$subhost.':';
  857:                print $logfile 
  858:                 "\nNotifying host for metadata only '.$subhost.':'";
  859:                my $reply=&Apache::lonnet::critical(
  860:                                 'update:'.$target.'.meta',$subhost);
  861:                $scrout.=$reply;
  862:                print $logfile $reply;              
  863:            }
  864:        }
  865:     }
  866:     closedir(DIR);
  867: 
  868: }
  869: 
  870: # ------------------------------------------------ Provide link to new resource
  871: 
  872:     my $thisdistarget=$target;
  873:     $thisdistarget=~s/^$docroot//;
  874: 
  875:     my $thissrc=$source;
  876:     $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
  877: 
  878:     my $thissrcdir=$thissrc;
  879:     $thissrcdir=~s/\/[^\/]+$/\//;
  880: 
  881: 
  882:     return $warning.$scrout.
  883:       '<hr><a href="'.$thisdistarget.'"><font size=+2>View Target</font></a>'.
  884:       '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
  885:       '<p><a href="'.$thissrcdir.
  886:       '"><font size=+2>Back to Source Directory</font></a>';
  887: 
  888: }
  889: 
  890: # ================================================================ Main Handler
  891: 
  892: sub handler {
  893:   my $r=shift;
  894: 
  895:   if ($r->header_only) {
  896:      $r->content_type('text/html');
  897:      $r->send_http_header;
  898:      return OK;
  899:   }
  900: 
  901: # Get query string for limited number of parameters
  902: 
  903:     map {
  904:        my ($name, $value) = split(/=/,$_);
  905:        $value =~ tr/+/ /;
  906:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  907:        if ($name eq 'filename') {
  908:            unless ($ENV{'form.'.$name}) {
  909:               $ENV{'form.'.$name}=$value;
  910: 	   }
  911:        }
  912:     } (split(/&/,$ENV{'QUERY_STRING'}));
  913: 
  914: 
  915: # -------------------------------------------------------------- Check filename
  916: 
  917:   my $fn=$ENV{'form.filename'};
  918: 
  919:   
  920:   unless ($fn) { 
  921:      $r->log_reason($cuname.' at '.$cudom.
  922:          ' trying to publish empty filename', $r->filename); 
  923:      return HTTP_NOT_FOUND;
  924:   } 
  925: 
  926:   ($cuname,$cudom)=
  927:     &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
  928:   unless (($cuname) && ($cudom)) {
  929:      $r->log_reason($cuname.' at '.$cudom.
  930:          ' trying to publish file '.$ENV{'form.filename'}.
  931:          ' ('.$fn.') - not authorized', 
  932:          $r->filename); 
  933:      return HTTP_NOT_ACCEPTABLE;
  934:   }
  935: 
  936:   unless (&Apache::lonnet::homeserver($cuname,$cudom) 
  937:           eq $r->dir_config('lonHostID')) {
  938:      $r->log_reason($cuname.' at '.$cudom.
  939:          ' trying to publish file '.$ENV{'form.filename'}.
  940:          ' ('.$fn.') - not homeserver ('.
  941:          &Apache::lonnet::homeserver($cuname,$cudom).')', 
  942:          $r->filename); 
  943:      return HTTP_NOT_ACCEPTABLE;
  944:   }
  945: 
  946:   $fn=~s/^http\:\/\/[^\/]+//;
  947:   $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
  948: 
  949:   my $targetdir='';
  950:   $docroot=$r->dir_config('lonDocRoot'); 
  951:   if ($1 ne $cuname) {
  952:      $r->log_reason($cuname.' at '.$cudom.
  953:          ' trying to publish unowned file '.$ENV{'form.filename'}.
  954:          ' ('.$fn.')', 
  955:          $r->filename); 
  956:      return HTTP_NOT_ACCEPTABLE;
  957:   } else {
  958:       $targetdir=$docroot.'/res/'.$cudom;
  959:   }
  960:                                  
  961:   
  962:   unless (-e $fn) { 
  963:      $r->log_reason($cuname.' at '.$cudom.
  964:          ' trying to publish non-existing file '.$ENV{'form.filename'}.
  965:          ' ('.$fn.')', 
  966:          $r->filename); 
  967:      return HTTP_NOT_FOUND;
  968:   } 
  969: 
  970: unless ($ENV{'form.phase'} eq 'two') {
  971: 
  972: # --------------------------------- File is there and owned, init lookup tables
  973: 
  974:   %addid=();
  975: 
  976:   {
  977:       my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
  978:       while (<$fh>=~/(\w+)\s+(\w+)/) {
  979:           $addid{$1}=$2;
  980:       }
  981:   }
  982: 
  983:   %nokey=();
  984: 
  985:   {
  986:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
  987:       map {
  988:           my $word=$_;
  989:           chomp($word);
  990:           $nokey{$word}=1;
  991:       } <$fh>;
  992:   }
  993: 
  994:   %language=();
  995: 
  996:   {
  997:      my $fh=Apache::File->new($r->dir_config('lonTabDir').'/language.tab');
  998:       map {
  999:           $_=~/(\w+)\s+([\w\s\-]+)/;
 1000:           $language{$1}=$2;
 1001:       } <$fh>;
 1002:   }
 1003: 
 1004:   %cprtag=();
 1005: 
 1006:   {
 1007:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/copyright.tab');
 1008:       map {
 1009:           $_=~/(\w+)\s+([\w\s\-]+)/;
 1010:           $cprtag{$1}=$2;
 1011:       } <$fh>;
 1012:   }
 1013: 
 1014: }
 1015: 
 1016: # ----------------------------------------------------------- Start page output
 1017: 
 1018:   $r->content_type('text/html');
 1019:   $r->send_http_header;
 1020: 
 1021:   $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
 1022:   $r->print(
 1023:    '<body bgcolor="#FFFFFF"><img align=right src=/adm/lonIcons/lonlogos.gif>');
 1024:   my $thisfn=$fn;
 1025:    
 1026: # ------------------------------------------------------------- Individual file
 1027:   {
 1028:       $thisfn=~/\.(\w+)$/;
 1029:       my $thistype=$1;
 1030:       my $thisembstyle=&Apache::lonnet::fileembstyle($thistype);
 1031: 
 1032:       my $thistarget=$thisfn;
 1033:       
 1034:       $thistarget=~s/^\/home/$targetdir/;
 1035:       $thistarget=~s/\/public\_html//;
 1036: 
 1037:       my $thisdistarget=$thistarget;
 1038:       $thisdistarget=~s/^$docroot//;
 1039: 
 1040:       my $thisdisfn=$thisfn;
 1041:       $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
 1042: 
 1043:       $r->print('<h2>Publishing '.
 1044:         &Apache::lonnet::filedescription($thistype).' <tt>'.
 1045:         $thisdisfn.'</tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
 1046:    
 1047:        if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
 1048:           $r->print('<h3><font color=red>Co-Author: '.$cuname.' at '.$cudom.
 1049:                '</font></h3>');
 1050:       }
 1051: 
 1052:       if (&Apache::lonnet::fileembstyle($thistype) eq 'ssi') {
 1053:           $r->print('<br><a href="/adm/diff?filename=/~'.$cuname.'/'.
 1054:                     $thisdisfn.
 1055:   	  '&versionone=priv" target=cat>Diffs with Current Version</a><p>');
 1056:       }
 1057:   
 1058: # ------------ We are publishing from $thisfn to $thistarget with $thisembstyle
 1059: 
 1060:        unless ($ENV{'form.phase'} eq 'two') {
 1061:          $r->print(
 1062:           '<hr>'.&publish($thisfn,$thistarget,$thisembstyle));
 1063:        } else {
 1064:          $r->print(
 1065:           '<hr>'.&phasetwo($thisfn,$thistarget,$thisembstyle,$thisdistarget)); 
 1066:        }  
 1067: 
 1068:   }
 1069:   $r->print('</body></html>');
 1070: 
 1071:   return OK;
 1072: }
 1073: 
 1074: 1;
 1075: __END__
 1076: 
 1077: 
 1078: 
 1079: 
 1080: 
 1081: 
 1082: 

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