File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.57: download - view: text, annotated - select for diffs
Wed Dec 5 20:25:20 2001 UTC (22 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- should work with <tag /> properly now.

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.57 2001/12/05 20:25:20 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: 		  if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  335: 		  $outstring.='<'.$tag.$newparmstring.$endtag.'>';
  336: 	         } else {
  337: 		   $allow{$token->[2]->{'src'}}=1;
  338: 		 }
  339:               } elsif ($token->[0] eq 'E') {
  340: 		if ($token->[2]) {
  341:                   unless ($token->[1] eq 'allow') {
  342:                      $outstring.='</'.$token->[1].'>';
  343: 		  }
  344: 		}
  345:               } else {
  346:                   $outstring.=$token->[1];
  347:               }
  348:           }
  349: # ------------------------------------------------------------ Construct Allows
  350:      unless ($style eq 'rat') {
  351: 	$scrout.='<h3>Dependencies</h3>';
  352: 	my $allowstr="\n";
  353:         map {
  354:            $allowstr.='<allow src="'.$_.'" />'."\n";
  355:            $scrout.='<br>';
  356:            unless ($_=~/\*/) {
  357: 	       $scrout.='<a href="'.$_.'">';
  358:            }
  359:            $scrout.='<tt>'.$_.'</tt>';
  360:            unless ($_=~/\*/) {
  361: 	       $scrout.='</a>';
  362:            }
  363:         } keys %allow;
  364:         $outstring=~s/(\<\/[^\>]+\>\s*)$/$allowstr$1/s;
  365:     }
  366: # ------------------------------------------------------------- Write modified
  367: 
  368:         {
  369:           my $org;
  370:           unless ($org=Apache::File->new('>'.$source)) {
  371:              print $logfile "No write permit to $source\n";
  372:              return 
  373:               "<font color=red>No write permission to $source, FAIL</font>";
  374: 	  }
  375:           print $org $outstring;
  376:         }
  377: 	  $content=$outstring;
  378: 
  379:       if ($needsfixup) {
  380:           print $logfile "End of ID and/or index fixup\n".
  381: 	        "Max ID   : $maxid (min 10)\n".
  382:                 "Max Index: $maxindex (min 10)\n";
  383:       } else {
  384: 	  print $logfile "Does not need ID and/or index fixup\n";
  385:       }
  386:     }
  387: # --------------------------------------------- Initial step done, now metadata
  388: 
  389: # ---------------------------------------- Storage for metadata keys and fields
  390: 
  391:      %metadatafields=();
  392:      %metadatakeys=();
  393:      
  394:      my %oldparmstores=();
  395:      
  396:      $scrout.='<h3>Metadata Information</h3>';
  397: 
  398: # ------------------------------------------------ First, check out environment
  399:      unless (-e $source.'.meta') {
  400:         $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
  401: 	                          $ENV{'environment.middlename'}.' '.
  402: 		                  $ENV{'environment.lastname'}.' '.
  403: 		                  $ENV{'environment.generation'};
  404:         $metadatafields{'author'}=~s/\s+/ /g;
  405:         $metadatafields{'author'}=~s/\s+$//;
  406:         $metadatafields{'owner'}=$cuname.'@'.$cudom;
  407: 
  408: # ------------------------------------------------ Check out directory hierachy
  409: 
  410:         my $thisdisfn=$source;
  411:         $thisdisfn=~s/^\/home\/$cuname\///;
  412: 
  413:         my @urlparts=split(/\//,$thisdisfn);
  414:         $#urlparts--;
  415: 
  416:         my $currentpath='/home/'.$cuname.'/';
  417: 
  418:         map {
  419: 	    $currentpath.=$_.'/';
  420:             $scrout.=&metaread($logfile,$currentpath.'default.meta');
  421:         } @urlparts;
  422: 
  423: # ------------------- Clear out parameters and stores (there should not be any)
  424: 
  425:         map {
  426: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  427: 		delete $metadatafields{$_};
  428:             }
  429:         } keys %metadatafields;
  430: 
  431:     } else {
  432: # ---------------------- Read previous metafile, remember parameters and stores
  433: 
  434:         $scrout.=&metaread($logfile,$source.'.meta');
  435: 
  436:         map {
  437: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  438:                 $oldparmstores{$_}=1;
  439: 		delete $metadatafields{$_};
  440:             }
  441:         } keys %metadatafields;
  442:         
  443:     }
  444: 
  445: # -------------------------------------------------- Parse content for metadata
  446:     if ($style eq 'ssi') {
  447:         my $oldenv=$ENV{'request.uri'};
  448: 
  449:         $ENV{'request.uri'}=$target;
  450:         $allmeta=Apache::lonxml::xmlparse('meta',$content);
  451:         $ENV{'request.uri'}=$oldenv;
  452: 
  453:         &metaeval($allmeta);
  454:     }
  455: # ---------------- Find and document discrepancies in the parameters and stores
  456: 
  457:         my $chparms='';
  458:         map {
  459: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  460:                 unless ($_=~/\.\w+$/) { 
  461:                    unless ($oldparmstores{$_}) {
  462: 		      print $logfile 'New: '.$_."\n";
  463:                       $chparms.=$_.' ';
  464:                    }
  465: 	        }
  466:             }
  467:         } sort keys %metadatafields;
  468:         if ($chparms) {
  469: 	    $scrout.='<p><b>New parameters or stored values:</b> '.
  470:                      $chparms;
  471:         }
  472: 
  473:         my $chparms='';
  474:         map {
  475: 	    if (($_=~/^parameter/) || ($_=~/^stores/)) {
  476:                 unless (($metadatafields{$_.'.name'}) ||
  477:                         ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
  478: 		    print $logfile 'Obsolete: '.$_."\n";
  479:                     $chparms.=$_.' ';
  480:                 }
  481:             }
  482:         } sort keys %oldparmstores;
  483:         if ($chparms) {
  484: 	    $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
  485:                      $chparms;
  486:         }
  487: 
  488: # ------------------------------------------------------- Now have all metadata
  489: 
  490:         $scrout.=
  491:      '<form action="/adm/publish" method="post">'.
  492:           &hiddenfield('phase','two').
  493:           &hiddenfield('filename',$ENV{'form.filename'}).
  494: 	  &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
  495:           &textfield('Title','title',$metadatafields{'title'}).
  496:           &textfield('Author(s)','author',$metadatafields{'author'}).
  497: 	  &textfield('Subject','subject',$metadatafields{'subject'});
  498: 
  499: # --------------------------------------------------- Scan content for keywords
  500: 
  501: 	my $keywordout='<p><b>Keywords:</b><br><table border=2><tr>';
  502:         my $colcount=0;
  503:         
  504: 	if (length($content)<500000) {
  505: 	    my $textonly=$content;
  506:             $textonly=~s/\<script[^\<]+\<\/script\>//g;
  507:             $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
  508:             $textonly=~s/\<[^\>]*\>//g;
  509:             $textonly=~tr/A-Z/a-z/;
  510:             $textonly=~s/[\$\&][a-z]\w*//g;
  511:             $textonly=~s/[^a-z\s]//g;
  512: 
  513:             my %keywords=();
  514:             map {
  515: 		unless ($nokey{$_}) {
  516:                    $keywords{$_}=1;
  517:                 } 
  518:             } ($textonly=~m/(\w+)/g);
  519: 
  520:             map {
  521: 		$keywords{$_}=1;
  522:             } split(/\W+/,$metadatafields{'keywords'});
  523: 
  524:             map {
  525:                 $keywordout.='<td><input type=checkbox name="key.'.$_.'"';
  526:                 if ($metadatafields{'keywords'}=~/$_/) { 
  527:                    $keywordout.=' checked'; 
  528:                 }
  529:                 $keywordout.='>'.$_.'</td>';
  530:                 if ($colcount>10) {
  531: 		    $keywordout.="</tr><tr>\n";
  532:                     $colcount=0;
  533:                 }
  534:                 $colcount++;
  535:             } sort keys %keywords;
  536: 
  537:         } else {
  538: 	    $keywordout.='<td>File too long for keyword analysis</td>';
  539:         }         
  540:         
  541: 	$keywordout.='</tr></table>';
  542: 
  543:         $scrout.=$keywordout;
  544: 
  545:         $scrout.=&textfield('Additional Keywords','addkey','');
  546: 
  547:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
  548: 
  549:         $scrout.=
  550:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
  551:               $metadatafields{'abstract'}.'</textarea>';
  552: 
  553: 	$source=~/\.(\w+)$/;
  554: 
  555: 	$scrout.=&hiddenfield('mime',$1);
  556: 
  557:         $scrout.=&selectbox('Language','language',
  558:                             $metadatafields{'language'},%language);
  559: 
  560:         unless ($metadatafields{'creationdate'}) {
  561: 	    $metadatafields{'creationdate'}=time;
  562:         }
  563:         $scrout.=&hiddenfield('creationdate',$metadatafields{'creationdate'});
  564: 
  565:         $scrout.=&hiddenfield('lastrevisiondate',time);
  566: 
  567: 			   
  568: 	$scrout.=&textfield('Publisher/Owner','owner',
  569:                             $metadatafields{'owner'});
  570: # --------------------------------------------------- Correct copyright for rat        
  571:     if ($style eq 'rat') {
  572:        if ($metadatafields{'copyright'} eq 'public') { 
  573:           delete $metadatafields{'copyright'};
  574:        }
  575:        delete $cprtag{'public'};
  576:    }
  577: 
  578:         $scrout.=&selectbox('Copyright/Distribution','copyright',
  579:                             $metadatafields{'copyright'},%cprtag);
  580: 
  581:     return $scrout.
  582:       '<p><input type="submit" value="Finalize Publication"></form>';
  583: }
  584: 
  585: # -------------------------------------------------------- Publication Step Two
  586: 
  587: sub phasetwo {
  588: 
  589:     my ($source,$target,$style,$distarget)=@_;
  590:     my $logfile;
  591:     my $scrout='';
  592: 
  593:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  594: 	return 
  595:          '<font color=red>No write permission to user directory, FAIL</font>';
  596:     }
  597:     print $logfile 
  598: "\n================= Publish ".localtime()." Phase Two  ================\n";
  599: 
  600:      %metadatafields=();
  601:      %metadatakeys=();
  602: 
  603:      &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
  604: 
  605:      $metadatafields{'title'}=$ENV{'form.title'};
  606:      $metadatafields{'author'}=$ENV{'form.author'};
  607:      $metadatafields{'subject'}=$ENV{'form.subject'};
  608:      $metadatafields{'notes'}=$ENV{'form.notes'};
  609:      $metadatafields{'abstract'}=$ENV{'form.abstract'};
  610:      $metadatafields{'mime'}=$ENV{'form.mime'};
  611:      $metadatafields{'language'}=$ENV{'form.language'};
  612:      $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
  613:      $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
  614:      $metadatafields{'owner'}=$ENV{'form.owner'};
  615:      $metadatafields{'copyright'}=$ENV{'form.copyright'};
  616: 
  617:      my $allkeywords=$ENV{'form.addkey'};
  618:      map {
  619:          if ($_=~/^form\.key\.(\w+)/) {
  620: 	     $allkeywords.=','.$1;
  621:          }
  622:      } keys %ENV;
  623:      $allkeywords=~s/\W+/\,/;
  624:      $allkeywords=~s/^\,//;
  625:      $metadatafields{'keywords'}=$allkeywords;
  626:  
  627:      {
  628:        print $logfile "\nWrite metadata file for ".$source;
  629:        my $mfh;
  630:        unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
  631: 	return 
  632:          '<font color=red>Could not write metadata, FAIL</font>';
  633:        }    
  634:        map {
  635: 	 unless ($_=~/\./) {
  636:            my $unikey=$_;
  637:            $unikey=~/^([A-Za-z]+)/;
  638:            my $tag=$1;
  639:            $tag=~tr/A-Z/a-z/;
  640:            print $mfh "\n\<$tag";
  641:            map {
  642:                my $value=$metadatafields{$unikey.'.'.$_};
  643:                $value=~s/\"/\'\'/g;
  644:                print $mfh ' '.$_.'="'.$value.'"';
  645:            } split(/\,/,$metadatakeys{$unikey});
  646: 	   print $mfh '>'.$metadatafields{$unikey}.'</'.$tag.'>';
  647:          }
  648:        } sort keys %metadatafields;
  649:        $scrout.='<p>Wrote Metadata';
  650:        print $logfile "\nWrote metadata";
  651:      }
  652: 
  653: # -------------------------------- Synchronize entry with SQL metadata database
  654:     my %perlvar;
  655:     open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
  656:     my $configline;
  657:     while ($configline=<CONFIG>) {
  658: 	if ($configline =~ /PerlSetVar/) {
  659: 	    my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
  660: 	    chomp($varvalue);
  661: 	    $perlvar{$varname}=$varvalue;
  662: 	}
  663:     }
  664:     close(CONFIG);
  665: 
  666:     my $warning;
  667:     my $dbh;
  668:     {
  669: 	unless (
  670: 		$dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  671: 		) { 
  672: 	    $warning='<font color=red>WARNING: Cannot connect to '.
  673: 		'database!</font>';
  674: 	}
  675: 	else {
  676: 	    my %sqldatafields;
  677: 	    $sqldatafields{'url'}=$distarget;
  678: 	    my $sth=$dbh->prepare(
  679: 				  'delete from metadata where url like binary'.
  680: 				  '"'.$sqldatafields{'url'}.'"');
  681: 	    $sth->execute();
  682: 	    map {my $field=$metadatafields{$_}; $field=~s/\"/\'\'/g; 
  683: 		 $sqldatafields{$_}=$field;}
  684: 	    ('title','author','subject','keywords','notes','abstract',
  685: 	     'mime','language','creationdate','lastrevisiondate','owner',
  686: 	     'copyright');
  687: 	    
  688: 	    $sth=$dbh->prepare('insert into metadata values ('.
  689: 			       '"'.delete($sqldatafields{'title'}).'"'.','.
  690: 			       '"'.delete($sqldatafields{'author'}).'"'.','.
  691: 			       '"'.delete($sqldatafields{'subject'}).'"'.','.
  692: 			       '"'.delete($sqldatafields{'url'}).'"'.','.
  693: 			       '"'.delete($sqldatafields{'keywords'}).'"'.','.
  694: 			       '"'.'current'.'"'.','.
  695: 			       '"'.delete($sqldatafields{'notes'}).'"'.','.
  696: 			       '"'.delete($sqldatafields{'abstract'}).'"'.','.
  697: 			       '"'.delete($sqldatafields{'mime'}).'"'.','.
  698: 			       '"'.delete($sqldatafields{'language'}).'"'.','.
  699: 			       '"'.
  700: 			       sqltime(delete($sqldatafields{'creationdate'}))
  701: 			       .'"'.','.
  702: 			       '"'.
  703: 			       sqltime(delete(
  704: 			       $sqldatafields{'lastrevisiondate'})).'"'.','.
  705: 			       '"'.delete($sqldatafields{'owner'}).'"'.','.
  706: 			       '"'.delete(
  707: 			       $sqldatafields{'copyright'}).'"'.')');
  708: 	    $sth->execute();
  709: 	    $dbh->disconnect;
  710: 	    $scrout.='<p>Synchronized SQL metadata database';
  711: 	    print $logfile "\nSynchronized SQL metadata database";
  712: 	}
  713:     }
  714: 
  715: 
  716: # ----------------------------------------------------------- Copy old versions
  717:    
  718: if (-e $target) {
  719:     my $filename;
  720:     my $maxversion=0;
  721:     $target=~/(.*)\/([^\/]+)\.(\w+)$/;
  722:     my $srcf=$2;
  723:     my $srct=$3;
  724:     my $srcd=$1;
  725:     unless ($srcd=~/^\/home\/httpd\/html\/res/) {
  726: 	print $logfile "\nPANIC: Target dir is ".$srcd;
  727:         return "<font color=red>Invalid target directory, FAIL</font>";
  728:     }
  729:     opendir(DIR,$srcd);
  730:     while ($filename=readdir(DIR)) {
  731:        if ($filename=~/$srcf\.(\d+)\.$srct$/) {
  732: 	   $maxversion=($1>$maxversion)?$1:$maxversion;
  733:        }
  734:     }
  735:     closedir(DIR);
  736:     $maxversion++;
  737:     $scrout.='<p>Creating old version '.$maxversion;
  738:     print $logfile "\nCreating old version ".$maxversion;
  739: 
  740:     my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
  741: 
  742:         if (copy($target,$copyfile)) {
  743: 	    print $logfile "Copied old target to ".$copyfile."\n";
  744:             $scrout.='<p>Copied old target file';
  745:         } else {
  746: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
  747:            return "<font color=red>Failed to copy old target, $!, FAIL</font>";
  748:         }
  749: 
  750: # --------------------------------------------------------------- Copy Metadata
  751: 
  752: 	$copyfile=$copyfile.'.meta';
  753: 
  754:         if (copy($target.'.meta',$copyfile)) {
  755: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
  756:             $scrout.='<p>Copied old metadata';
  757:         } else {
  758: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
  759:             if (-e $target.'.meta') {
  760:                return 
  761:        "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
  762: 	    }
  763:         }
  764: 
  765: 
  766: } else {
  767:     $scrout.='<p>Initial version';
  768:     print $logfile "\nInitial version";
  769: }
  770: 
  771: # ---------------------------------------------------------------- Write Source
  772: 	my $copyfile=$target;
  773: 
  774:            my @parts=split(/\//,$copyfile);
  775:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  776: 
  777:            my $count;
  778:            for ($count=5;$count<$#parts;$count++) {
  779:                $path.="/$parts[$count]";
  780:                if ((-e $path)!=1) {
  781:                    print $logfile "\nCreating directory ".$path;
  782:                    $scrout.='<p>Created directory '.$parts[$count];
  783: 		   mkdir($path,0777);
  784:                }
  785:            }
  786: 
  787:         if (copy($source,$copyfile)) {
  788: 	    print $logfile "Copied original source to ".$copyfile."\n";
  789:             $scrout.='<p>Copied source file';
  790:         } else {
  791: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
  792:             return "<font color=red>Failed to copy source, $!, FAIL</font>";
  793:         }
  794: 
  795: # --------------------------------------------------------------- Copy Metadata
  796: 
  797:         $copyfile=$copyfile.'.meta';
  798: 
  799:         if (copy($source.'.meta',$copyfile)) {
  800: 	    print $logfile "Copied original metadata to ".$copyfile."\n";
  801:             $scrout.='<p>Copied metadata';
  802:         } else {
  803: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
  804:             return 
  805:           "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
  806:         }
  807: 
  808: # --------------------------------------------------- Send update notifications
  809: 
  810: {
  811: 
  812:     my $filename;
  813:  
  814:     $target=~/(.*)\/([^\/]+)$/;
  815:     my $srcf=$2;
  816:     opendir(DIR,$1);
  817:     while ($filename=readdir(DIR)) {
  818:        if ($filename=~/$srcf\.(\w+)$/) {
  819: 	   my $subhost=$1;
  820:            if ($subhost ne 'meta') {
  821: 	       $scrout.='<p>Notifying host '.$subhost.':';
  822:                print $logfile "\nNotifying host '.$subhost.':'";
  823:                my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
  824:                $scrout.=$reply;
  825:                print $logfile $reply;              
  826:            }
  827:        }
  828:     }
  829:     closedir(DIR);
  830: 
  831: }
  832: 
  833: # ---------------------------------------- Send update notifications, meta only
  834: 
  835: {
  836: 
  837:     my $filename;
  838:  
  839:     $target=~/(.*)\/([^\/]+)$/;
  840:     my $srcf=$2.'.meta';
  841:     opendir(DIR,$1);
  842:     while ($filename=readdir(DIR)) {
  843:        if ($filename=~/$srcf\.(\w+)$/) {
  844: 	   my $subhost=$1;
  845:            if ($subhost ne 'meta') {
  846: 	       $scrout.=
  847:                 '<p>Notifying host for metadata only '.$subhost.':';
  848:                print $logfile 
  849:                 "\nNotifying host for metadata only '.$subhost.':'";
  850:                my $reply=&Apache::lonnet::critical(
  851:                                 'update:'.$target.'.meta',$subhost);
  852:                $scrout.=$reply;
  853:                print $logfile $reply;              
  854:            }
  855:        }
  856:     }
  857:     closedir(DIR);
  858: 
  859: }
  860: 
  861: # ------------------------------------------------ Provide link to new resource
  862: 
  863:     my $thisdistarget=$target;
  864:     $thisdistarget=~s/^$docroot//;
  865: 
  866:     my $thissrc=$source;
  867:     $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
  868: 
  869:     my $thissrcdir=$thissrc;
  870:     $thissrcdir=~s/\/[^\/]+$/\//;
  871: 
  872: 
  873:     return $warning.$scrout.
  874:       '<hr><a href="'.$thisdistarget.'"><font size=+2>View Target</font></a>'.
  875:       '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
  876:       '<p><a href="'.$thissrcdir.
  877:       '"><font size=+2>Back to Source Directory</font></a>';
  878: 
  879: }
  880: 
  881: # ================================================================ Main Handler
  882: 
  883: sub handler {
  884:   my $r=shift;
  885: 
  886:   if ($r->header_only) {
  887:      $r->content_type('text/html');
  888:      $r->send_http_header;
  889:      return OK;
  890:   }
  891: 
  892: # Get query string for limited number of parameters
  893: 
  894:     map {
  895:        my ($name, $value) = split(/=/,$_);
  896:        $value =~ tr/+/ /;
  897:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  898:        if ($name eq 'filename') {
  899:            unless ($ENV{'form.'.$name}) {
  900:               $ENV{'form.'.$name}=$value;
  901: 	   }
  902:        }
  903:     } (split(/&/,$ENV{'QUERY_STRING'}));
  904: 
  905: 
  906: # -------------------------------------------------------------- Check filename
  907: 
  908:   my $fn=$ENV{'form.filename'};
  909: 
  910:   
  911:   unless ($fn) { 
  912:      $r->log_reason($cuname.' at '.$cudom.
  913:          ' trying to publish empty filename', $r->filename); 
  914:      return HTTP_NOT_FOUND;
  915:   } 
  916: 
  917:   ($cuname,$cudom)=
  918:     &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
  919:   unless (($cuname) && ($cudom)) {
  920:      $r->log_reason($cuname.' at '.$cudom.
  921:          ' trying to publish file '.$ENV{'form.filename'}.
  922:          ' ('.$fn.') - not authorized', 
  923:          $r->filename); 
  924:      return HTTP_NOT_ACCEPTABLE;
  925:   }
  926: 
  927:   unless (&Apache::lonnet::homeserver($cuname,$cudom) 
  928:           eq $r->dir_config('lonHostID')) {
  929:      $r->log_reason($cuname.' at '.$cudom.
  930:          ' trying to publish file '.$ENV{'form.filename'}.
  931:          ' ('.$fn.') - not homeserver ('.
  932:          &Apache::lonnet::homeserver($cuname,$cudom).')', 
  933:          $r->filename); 
  934:      return HTTP_NOT_ACCEPTABLE;
  935:   }
  936: 
  937:   $fn=~s/^http\:\/\/[^\/]+//;
  938:   $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
  939: 
  940:   my $targetdir='';
  941:   $docroot=$r->dir_config('lonDocRoot'); 
  942:   if ($1 ne $cuname) {
  943:      $r->log_reason($cuname.' at '.$cudom.
  944:          ' trying to publish unowned file '.$ENV{'form.filename'}.
  945:          ' ('.$fn.')', 
  946:          $r->filename); 
  947:      return HTTP_NOT_ACCEPTABLE;
  948:   } else {
  949:       $targetdir=$docroot.'/res/'.$cudom;
  950:   }
  951:                                  
  952:   
  953:   unless (-e $fn) { 
  954:      $r->log_reason($cuname.' at '.$cudom.
  955:          ' trying to publish non-existing file '.$ENV{'form.filename'}.
  956:          ' ('.$fn.')', 
  957:          $r->filename); 
  958:      return HTTP_NOT_FOUND;
  959:   } 
  960: 
  961: unless ($ENV{'form.phase'} eq 'two') {
  962: 
  963: # --------------------------------- File is there and owned, init lookup tables
  964: 
  965:   %addid=();
  966: 
  967:   {
  968:       my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
  969:       while (<$fh>=~/(\w+)\s+(\w+)/) {
  970:           $addid{$1}=$2;
  971:       }
  972:   }
  973: 
  974:   %nokey=();
  975: 
  976:   {
  977:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
  978:       map {
  979:           my $word=$_;
  980:           chomp($word);
  981:           $nokey{$word}=1;
  982:       } <$fh>;
  983:   }
  984: 
  985:   %language=();
  986: 
  987:   {
  988:      my $fh=Apache::File->new($r->dir_config('lonTabDir').'/language.tab');
  989:       map {
  990:           $_=~/(\w+)\s+([\w\s\-]+)/;
  991:           $language{$1}=$2;
  992:       } <$fh>;
  993:   }
  994: 
  995:   %cprtag=();
  996: 
  997:   {
  998:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/copyright.tab');
  999:       map {
 1000:           $_=~/(\w+)\s+([\w\s\-]+)/;
 1001:           $cprtag{$1}=$2;
 1002:       } <$fh>;
 1003:   }
 1004: 
 1005: }
 1006: 
 1007: # ----------------------------------------------------------- Start page output
 1008: 
 1009:   $r->content_type('text/html');
 1010:   $r->send_http_header;
 1011: 
 1012:   $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
 1013:   $r->print(
 1014:    '<body bgcolor="#FFFFFF"><img align=right src=/adm/lonIcons/lonlogos.gif>');
 1015:   my $thisfn=$fn;
 1016:    
 1017: # ------------------------------------------------------------- Individual file
 1018:   {
 1019:       $thisfn=~/\.(\w+)$/;
 1020:       my $thistype=$1;
 1021:       my $thisembstyle=&Apache::lonnet::fileembstyle($thistype);
 1022: 
 1023:       my $thistarget=$thisfn;
 1024:       
 1025:       $thistarget=~s/^\/home/$targetdir/;
 1026:       $thistarget=~s/\/public\_html//;
 1027: 
 1028:       my $thisdistarget=$thistarget;
 1029:       $thisdistarget=~s/^$docroot//;
 1030: 
 1031:       my $thisdisfn=$thisfn;
 1032:       $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
 1033: 
 1034:       $r->print('<h2>Publishing '.
 1035:         &Apache::lonnet::filedescription($thistype).' <tt>'.
 1036:         $thisdisfn.'</tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
 1037:    
 1038:        if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
 1039:           $r->print('<h3><font color=red>Co-Author: '.$cuname.' at '.$cudom.
 1040:                '</font></h3>');
 1041:       }
 1042: 
 1043:       if (&Apache::lonnet::fileembstyle($thistype) eq 'ssi') {
 1044:           $r->print('<br><a href="/adm/diff?filename=/~'.$cuname.'/'.
 1045:                     $thisdisfn.
 1046:   	  '&versionone=priv" target=cat>Diffs with Current Version</a><p>');
 1047:       }
 1048:   
 1049: # ------------ We are publishing from $thisfn to $thistarget with $thisembstyle
 1050: 
 1051:        unless ($ENV{'form.phase'} eq 'two') {
 1052:          $r->print(
 1053:           '<hr>'.&publish($thisfn,$thistarget,$thisembstyle));
 1054:        } else {
 1055:          $r->print(
 1056:           '<hr>'.&phasetwo($thisfn,$thistarget,$thisembstyle,$thisdistarget)); 
 1057:        }  
 1058: 
 1059:   }
 1060:   $r->print('</body></html>');
 1061: 
 1062:   return OK;
 1063: }
 1064: 
 1065: 1;
 1066: __END__
 1067: 
 1068: 
 1069: 
 1070: 
 1071: 
 1072: 
 1073: 

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