File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.56: download - view: text, annotated - select for diffs
Wed Dec 5 15:40:31 2001 UTC (22 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- now it actually lowercases

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

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