File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.44: download - view: text, annotated - select for diffs
Fri Aug 24 13:33:37 2001 UTC (22 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Lists dependencies and recognizes background images as such

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

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