File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.39: download - view: text, annotated - select for diffs
Fri Aug 17 16:27:08 2001 UTC (22 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug fix - empty URLs do not need fixup.

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

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