File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.53: download - view: text, annotated - select for diffs
Tue Dec 4 15:32:57 2001 UTC (22 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
 - prevent publisher from automatically downcasing all tags

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

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