File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.60: download - view: text, annotated - select for diffs
Wed Dec 5 21:17:56 2001 UTC (22 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Stores dependencies to metadata

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

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