File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.49: download - view: text, annotated - select for diffs
Tue Oct 16 18:46:10 2001 UTC (22 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Last version not so hot.

    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 Gerd Kortemeyer
   15: # 10/3,10/8 Scott Harrison
   16: 
   17: package Apache::lonpublisher;
   18: 
   19: use strict;
   20: use Apache::File;
   21: use File::Copy;
   22: use Apache::Constants qw(:common :http :methods);
   23: use HTML::TokeParser;
   24: use Apache::lonxml;
   25: use Apache::lonhomework;
   26: use Apache::loncacc;
   27: use DBI;
   28: 
   29: my %addid;
   30: my %nokey;
   31: my %language;
   32: my %cprtag;
   33: 
   34: my %metadatafields;
   35: my %metadatakeys;
   36: 
   37: my $docroot;
   38: 
   39: my $cuname;
   40: my $cudom;
   41: 
   42: # ----------------------------------------------- Evaluate string with metadata
   43: 
   44: sub metaeval {
   45:     my $metastring=shift;
   46:    
   47:         my $parser=HTML::TokeParser->new(\$metastring);
   48:         my $token;
   49:         while ($token=$parser->get_token) {
   50:            if ($token->[0] eq 'S') {
   51: 	      my $entry=$token->[1];
   52:               my $unikey=$entry;
   53:               if (defined($token->[2]->{'package'})) { 
   54:                   $unikey.='_package_'.$token->[2]->{'package'};
   55:               } 
   56:               if (defined($token->[2]->{'part'})) { 
   57:                  $unikey.='_'.$token->[2]->{'part'}; 
   58: 	      }
   59:               if (defined($token->[2]->{'id'})) { 
   60:                   $unikey.='_'.$token->[2]->{'id'};
   61:               } 
   62:               if (defined($token->[2]->{'name'})) { 
   63:                  $unikey.='_'.$token->[2]->{'name'}; 
   64: 	      }
   65:                map {
   66: 		  $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
   67:                   if ($metadatakeys{$unikey}) {
   68: 		      $metadatakeys{$unikey}.=','.$_;
   69:                   } else {
   70:                       $metadatakeys{$unikey}=$_;
   71:                   }
   72:               } @{$token->[3]};
   73:               if ($metadatafields{$unikey}) {
   74: 		  my $newentry=$parser->get_text('/'.$entry);
   75:                   unless (($metadatafields{$unikey}=~/$newentry/) ||
   76:                           ($newentry eq '')) {
   77:                      $metadatafields{$unikey}.=', '.$newentry;
   78: 		  }
   79: 	      } else {
   80:                  $metadatafields{$unikey}=$parser->get_text('/'.$entry);
   81:               }
   82:           }
   83:        }
   84: }
   85: 
   86: # -------------------------------------------------------- Read a metadata file
   87: 
   88: sub metaread {
   89:     my ($logfile,$fn)=@_;
   90:     unless (-e $fn) {
   91: 	print $logfile 'No file '.$fn."\n";
   92:         return '<br><b>No file:</b> <tt>'.$fn.'</tt>';
   93:     }
   94:     print $logfile 'Processing '.$fn."\n";
   95:     my $metastring;
   96:     {
   97:      my $metafh=Apache::File->new($fn);
   98:      $metastring=join('',<$metafh>);
   99:     }
  100:     &metaeval($metastring);
  101:     return '<br><b>Processed file:</b> <tt>'.$fn.'</tt>';
  102: }
  103: 
  104: # ---------------------------- convert 'time' format into a datetime sql format
  105: sub sqltime {
  106:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  107: 	localtime(@_[0]);
  108:     $mon++; $year+=1900;
  109:     return "$year-$mon-$mday $hour:$min:$sec";
  110: }
  111: 
  112: # --------------------------------------------------------- Various form fields
  113: 
  114: sub textfield {
  115:     my ($title,$name,$value)=@_;
  116:     return "\n<p><b>$title:</b><br>".
  117:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
  118: }
  119: 
  120: sub hiddenfield {
  121:     my ($name,$value)=@_;
  122:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
  123: }
  124: 
  125: sub selectbox {
  126:     my ($title,$name,$value,%options)=@_;
  127:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
  128:     map {
  129:         $selout.='<option value="'.$_.'"';
  130:         if ($_ eq $value) { $selout.=' selected'; }
  131:         $selout.='>'.$options{$_}.'</option>';
  132:     } sort keys %options;
  133:     return $selout.'</select>';
  134: }
  135: 
  136: # -------------------------------------------------------- Publication Step One
  137: 
  138: sub urlfixup {
  139:     my ($url,$target)=@_;
  140:     unless ($url) { return ''; }
  141:     my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
  142:     map {
  143: 	if ($_ eq $host) {
  144: 	    $url=~s/^http\:\/\///;
  145:             $url=~s/^$host//;
  146:         }
  147:     } values %Apache::lonnet::hostname;
  148:     if ($url=~/^http\:\/\//) { return $url; }
  149:     $url=~s/\~$cuname/res\/$cudom\/$cuname/;
  150:     if ($target) {
  151: 	$target=~s/\/[^\/]+$//;
  152:        $url=&Apache::lonnet::hreflocation($target,$url);
  153:     }
  154:     return $url;
  155: }
  156: 
  157: sub publish {
  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:             my $j=0;
  484:             my $word;
  485:             for (my $i=0; $i<length($textonly); $i++) {
  486: 		my $ch.=substr($textonly,$i,1);
  487: 		if ($ch=~/\s/) {
  488: 		    if (length($word)) {
  489: 			unless ($nokey{$word}) {
  490: 			    $keywords{$word}=1;
  491: 			}
  492: 		    }
  493: 		    $word='';
  494: 		}
  495: 		else {
  496: 		    $word.=$ch;
  497: 		}
  498: #		map {
  499: #		    unless ($nokey{$_}) {
  500: #			$keywords{$_}=1;
  501: #		    } 
  502: #		} ($textonly=~m/(\w+)/g);
  503: 	    }
  504: 
  505: 	    my $sizkeys=scalar(keys %keywords); # use this value at some point
  506:             map {
  507: 		$keywords{$_}=1;
  508:             } split(/\W+/,$metadatafields{'keywords'});
  509: 
  510:             map {
  511:                 $keywordout.='<td><input type=checkbox name="key.'.$_.'"';
  512:                 if ($metadatafields{'keywords'}=~/$_/) { 
  513:                    $keywordout.=' checked'; 
  514:                 }
  515:                 $keywordout.='>'.$_.'</td>';
  516:                 if ($colcount>10) {
  517: 		    $keywordout.="</tr><tr>\n";
  518:                     $colcount=0;
  519:                 }
  520: 		else {
  521: 		    $colcount++;
  522: 		}
  523:             } sort keys %keywords;
  524:             $keywordout.='</tr></table>';
  525: 
  526:         }         
  527: 	$scrout.=$keywordout;
  528: 
  529:         $scrout.=&textfield('Additional Keywords','addkey','');
  530: 
  531:         $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
  532: 
  533:         $scrout.=
  534:              '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
  535:               $metadatafields{'abstract'}.'</textarea>';
  536: 
  537: 	$source=~/\.(\w+)$/;
  538: 
  539: 	$scrout.=&hiddenfield('mime',$1);
  540: 
  541:         $scrout.=&selectbox('Language','language',
  542:                             $metadatafields{'language'},%language);
  543: 
  544:         unless ($metadatafields{'creationdate'}) {
  545: 	    $metadatafields{'creationdate'}=time;
  546:         }
  547:         $scrout.=&hiddenfield('creationdate',$metadatafields{'creationdate'});
  548: 
  549:         $scrout.=&hiddenfield('lastrevisiondate',time);
  550: 
  551: 			   
  552: 	$scrout.=&textfield('Publisher/Owner','owner',
  553:                             $metadatafields{'owner'});
  554: # --------------------------------------------------- Correct copyright for rat        
  555:     if ($style eq 'rat') {
  556:        if ($metadatafields{'copyright'} eq 'public') { 
  557:           delete $metadatafields{'copyright'};
  558:        }
  559:        delete $cprtag{'public'};
  560:    }
  561: 
  562:         $scrout.=&selectbox('Copyright/Distribution','copyright',
  563:                             $metadatafields{'copyright'},%cprtag);
  564: 
  565:     return $scrout.
  566:       '<p><input type="submit" value="Finalize Publication"></form>';
  567: }
  568: 
  569: # -------------------------------------------------------- Publication Step Two
  570: 
  571: sub phasetwo {
  572: 
  573:     my ($source,$target,$style,$distarget)=@_;
  574:     my $logfile;
  575:     my $scrout='';
  576: 
  577:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
  578: 	return 
  579:          '<font color=red>No write permission to user directory, FAIL</font>';
  580:     }
  581:     print $logfile 
  582: "\n================= Publish ".localtime()." Phase Two  ================\n";
  583: 
  584:      %metadatafields=();
  585:      %metadatakeys=();
  586: 
  587:      &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
  588: 
  589:      $metadatafields{'title'}=$ENV{'form.title'};
  590:      $metadatafields{'author'}=$ENV{'form.author'};
  591:      $metadatafields{'subject'}=$ENV{'form.subject'};
  592:      $metadatafields{'notes'}=$ENV{'form.notes'};
  593:      $metadatafields{'abstract'}=$ENV{'form.abstract'};
  594:      $metadatafields{'mime'}=$ENV{'form.mime'};
  595:      $metadatafields{'language'}=$ENV{'form.language'};
  596:      $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
  597:      $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
  598:      $metadatafields{'owner'}=$ENV{'form.owner'};
  599:      $metadatafields{'copyright'}=$ENV{'form.copyright'};
  600: 
  601:      my $allkeywords=$ENV{'form.addkey'};
  602:      map {
  603:          if ($_=~/^form\.key\.(\w+)/) {
  604: 	     $allkeywords.=','.$1;
  605:          }
  606:      } keys %ENV;
  607:      $allkeywords=~s/\W+/\,/;
  608:      $allkeywords=~s/^\,//;
  609:      $metadatafields{'keywords'}=$allkeywords;
  610:  
  611:      {
  612:        print $logfile "\nWrite metadata file for ".$source;
  613:        my $mfh;
  614:        unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
  615: 	return 
  616:          '<font color=red>Could not write metadata, FAIL</font>';
  617:        }    
  618:        map {
  619: 	 unless ($_=~/\./) {
  620:            my $unikey=$_;
  621:            $unikey=~/^([A-Za-z]+)/;
  622:            my $tag=$1;
  623:            $tag=~tr/A-Z/a-z/;
  624:            print $mfh "\n\<$tag";
  625:            map {
  626:                my $value=$metadatafields{$unikey.'.'.$_};
  627:                $value=~s/\"/\'\'/g;
  628:                print $mfh ' '.$_.'="'.$value.'"';
  629:            } split(/\,/,$metadatakeys{$unikey});
  630: 	   print $mfh '>'.$metadatafields{$unikey}.'</'.$tag.'>';
  631:          }
  632:        } sort keys %metadatafields;
  633:        $scrout.='<p>Wrote Metadata';
  634:        print $logfile "\nWrote metadata";
  635:      }
  636: 
  637: # -------------------------------- Synchronize entry with SQL metadata database
  638:     my %perlvar;
  639:     open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
  640:     my $configline;
  641:     while ($configline=<CONFIG>) {
  642: 	if ($configline =~ /PerlSetVar/) {
  643: 	    my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
  644: 	    chomp($varvalue);
  645: 	    $perlvar{$varname}=$varvalue;
  646: 	}
  647:     }
  648:     close(CONFIG);
  649: 
  650:     my $warning;
  651:     my $dbh;
  652:     {
  653: 	unless (
  654: 		$dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  655: 		) { 
  656: 	    $warning='<font color=red>WARNING: Cannot connect to '.
  657: 		'database!</font>';
  658: 	}
  659: 	else {
  660: 	    my %sqldatafields;
  661: 	    $sqldatafields{'url'}=$distarget;
  662: 	    my $sth=$dbh->prepare(
  663: 				  'delete from metadata where url like binary'.
  664: 				  '"'.$sqldatafields{'url'}.'"');
  665: 	    $sth->execute();
  666: 	    map {my $field=$metadatafields{$_}; $field=~s/\"/\'\'/g; 
  667: 		 $sqldatafields{$_}=$field;}
  668: 	    ('title','author','subject','keywords','notes','abstract',
  669: 	     'mime','language','creationdate','lastrevisiondate','owner',
  670: 	     'copyright');
  671: 	    
  672: 	    $sth=$dbh->prepare('insert into metadata values ('.
  673: 			       '"'.delete($sqldatafields{'title'}).'"'.','.
  674: 			       '"'.delete($sqldatafields{'author'}).'"'.','.
  675: 			       '"'.delete($sqldatafields{'subject'}).'"'.','.
  676: 			       '"'.delete($sqldatafields{'url'}).'"'.','.
  677: 			       '"'.delete($sqldatafields{'keywords'}).'"'.','.
  678: 			       '"'.'current'.'"'.','.
  679: 			       '"'.delete($sqldatafields{'notes'}).'"'.','.
  680: 			       '"'.delete($sqldatafields{'abstract'}).'"'.','.
  681: 			       '"'.delete($sqldatafields{'mime'}).'"'.','.
  682: 			       '"'.delete($sqldatafields{'language'}).'"'.','.
  683: 			       '"'.
  684: 			       sqltime(delete($sqldatafields{'creationdate'}))
  685: 			       .'"'.','.
  686: 			       '"'.
  687: 			       sqltime(delete(
  688: 			       $sqldatafields{'lastrevisiondate'})).'"'.','.
  689: 			       '"'.delete($sqldatafields{'owner'}).'"'.','.
  690: 			       '"'.delete(
  691: 			       $sqldatafields{'copyright'}).'"'.')');
  692: 	    $sth->execute();
  693: 	    $dbh->disconnect;
  694: 	    $scrout.='<p>Synchronized SQL metadata database';
  695: 	    print $logfile "\nSynchronized SQL metadata database";
  696: 	}
  697:     }
  698: 
  699: 
  700: # ----------------------------------------------------------- Copy old versions
  701:    
  702: if (-e $target) {
  703:     my $filename;
  704:     my $maxversion=0;
  705:     $target=~/(.*)\/([^\/]+)\.(\w+)$/;
  706:     my $srcf=$2;
  707:     my $srct=$3;
  708:     my $srcd=$1;
  709:     unless ($srcd=~/^\/home\/httpd\/html\/res/) {
  710: 	print $logfile "\nPANIC: Target dir is ".$srcd;
  711:         return "<font color=red>Invalid target directory, FAIL</font>";
  712:     }
  713:     opendir(DIR,$srcd);
  714:     while ($filename=readdir(DIR)) {
  715:        if ($filename=~/$srcf\.(\d+)\.$srct$/) {
  716: 	   $maxversion=($1>$maxversion)?$1:$maxversion;
  717:        }
  718:     }
  719:     closedir(DIR);
  720:     $maxversion++;
  721:     $scrout.='<p>Creating old version '.$maxversion;
  722:     print $logfile "\nCreating old version ".$maxversion;
  723: 
  724:     my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
  725: 
  726:         if (copy($target,$copyfile)) {
  727: 	    print $logfile "Copied old target to ".$copyfile."\n";
  728:             $scrout.='<p>Copied old target file';
  729:         } else {
  730: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
  731:            return "<font color=red>Failed to copy old target, $!, FAIL</font>";
  732:         }
  733: 
  734: # --------------------------------------------------------------- Copy Metadata
  735: 
  736: 	$copyfile=$copyfile.'.meta';
  737: 
  738:         if (copy($target.'.meta',$copyfile)) {
  739: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
  740:             $scrout.='<p>Copied old metadata';
  741:         } else {
  742: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
  743:             if (-e $target.'.meta') {
  744:                return 
  745:        "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
  746: 	    }
  747:         }
  748: 
  749: 
  750: } else {
  751:     $scrout.='<p>Initial version';
  752:     print $logfile "\nInitial version";
  753: }
  754: 
  755: # ---------------------------------------------------------------- Write Source
  756: 	my $copyfile=$target;
  757: 
  758:            my @parts=split(/\//,$copyfile);
  759:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  760: 
  761:            my $count;
  762:            for ($count=5;$count<$#parts;$count++) {
  763:                $path.="/$parts[$count]";
  764:                if ((-e $path)!=1) {
  765:                    print $logfile "\nCreating directory ".$path;
  766:                    $scrout.='<p>Created directory '.$parts[$count];
  767: 		   mkdir($path,0777);
  768:                }
  769:            }
  770: 
  771:         if (copy($source,$copyfile)) {
  772: 	    print $logfile "Copied original source to ".$copyfile."\n";
  773:             $scrout.='<p>Copied source file';
  774:         } else {
  775: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
  776:             return "<font color=red>Failed to copy source, $!, FAIL</font>";
  777:         }
  778: 
  779: # --------------------------------------------------------------- Copy Metadata
  780: 
  781:         $copyfile=$copyfile.'.meta';
  782: 
  783:         if (copy($source.'.meta',$copyfile)) {
  784: 	    print $logfile "Copied original metadata to ".$copyfile."\n";
  785:             $scrout.='<p>Copied metadata';
  786:         } else {
  787: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
  788:             return 
  789:           "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
  790:         }
  791: 
  792: # --------------------------------------------------- Send update notifications
  793: 
  794: {
  795: 
  796:     my $filename;
  797:  
  798:     $target=~/(.*)\/([^\/]+)$/;
  799:     my $srcf=$2;
  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.='<p>Notifying host '.$subhost.':';
  806:                print $logfile "\nNotifying host '.$subhost.':'";
  807:                my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
  808:                $scrout.=$reply;
  809:                print $logfile $reply;              
  810:            }
  811:        }
  812:     }
  813:     closedir(DIR);
  814: 
  815: }
  816: 
  817: # ---------------------------------------- Send update notifications, meta only
  818: 
  819: {
  820: 
  821:     my $filename;
  822:  
  823:     $target=~/(.*)\/([^\/]+)$/;
  824:     my $srcf=$2.'.meta';
  825:     opendir(DIR,$1);
  826:     while ($filename=readdir(DIR)) {
  827:        if ($filename=~/$srcf\.(\w+)$/) {
  828: 	   my $subhost=$1;
  829:            if ($subhost ne 'meta') {
  830: 	       $scrout.=
  831:                 '<p>Notifying host for metadata only '.$subhost.':';
  832:                print $logfile 
  833:                 "\nNotifying host for metadata only '.$subhost.':'";
  834:                my $reply=&Apache::lonnet::critical(
  835:                                 'update:'.$target.'.meta',$subhost);
  836:                $scrout.=$reply;
  837:                print $logfile $reply;              
  838:            }
  839:        }
  840:     }
  841:     closedir(DIR);
  842: 
  843: }
  844: 
  845: # ------------------------------------------------ Provide link to new resource
  846: 
  847:     my $thisdistarget=$target;
  848:     $thisdistarget=~s/^$docroot//;
  849: 
  850:     my $thissrc=$source;
  851:     $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
  852: 
  853:     my $thissrcdir=$thissrc;
  854:     $thissrcdir=~s/\/[^\/]+$/\//;
  855: 
  856: 
  857:     return $warning.$scrout.
  858:       '<hr><a href="'.$thisdistarget.'"><font size=+2>View Target</font></a>'.
  859:       '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
  860:       '<p><a href="'.$thissrcdir.
  861:       '"><font size=+2>Back to Source Directory</font></a>';
  862: 
  863: }
  864: 
  865: # ================================================================ Main Handler
  866: 
  867: sub handler {
  868:   my $r=shift;
  869: 
  870:   if ($r->header_only) {
  871:      $r->content_type('text/html');
  872:      $r->send_http_header;
  873:      return OK;
  874:   }
  875: 
  876: # Get query string for limited number of parameters
  877: 
  878:     map {
  879:        my ($name, $value) = split(/=/,$_);
  880:        $value =~ tr/+/ /;
  881:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  882:        if ($name eq 'filename') {
  883:            unless ($ENV{'form.'.$name}) {
  884:               $ENV{'form.'.$name}=$value;
  885: 	   }
  886:        }
  887:     } (split(/&/,$ENV{'QUERY_STRING'}));
  888: 
  889: 
  890: # -------------------------------------------------------------- Check filename
  891: 
  892:   my $fn=$ENV{'form.filename'};
  893: 
  894:   
  895:   unless ($fn) { 
  896:      $r->log_reason($cuname.' at '.$cudom.
  897:          ' trying to publish empty filename', $r->filename); 
  898:      return HTTP_NOT_FOUND;
  899:   } 
  900: 
  901:   ($cuname,$cudom)=
  902:     &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
  903:   unless (($cuname) && ($cudom)) {
  904:      $r->log_reason($cuname.' at '.$cudom.
  905:          ' trying to publish file '.$ENV{'form.filename'}.
  906:          ' ('.$fn.') - not authorized', 
  907:          $r->filename); 
  908:      return HTTP_NOT_ACCEPTABLE;
  909:   }
  910: 
  911:   unless (&Apache::lonnet::homeserver($cuname,$cudom) 
  912:           eq $r->dir_config('lonHostID')) {
  913:      $r->log_reason($cuname.' at '.$cudom.
  914:          ' trying to publish file '.$ENV{'form.filename'}.
  915:          ' ('.$fn.') - not homeserver ('.
  916:          &Apache::lonnet::homeserver($cuname,$cudom).')', 
  917:          $r->filename); 
  918:      return HTTP_NOT_ACCEPTABLE;
  919:   }
  920: 
  921:   $fn=~s/^http\:\/\/[^\/]+//;
  922:   $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
  923: 
  924:   my $targetdir='';
  925:   $docroot=$r->dir_config('lonDocRoot'); 
  926:   if ($1 ne $cuname) {
  927:      $r->log_reason($cuname.' at '.$cudom.
  928:          ' trying to publish unowned file '.$ENV{'form.filename'}.
  929:          ' ('.$fn.')', 
  930:          $r->filename); 
  931:      return HTTP_NOT_ACCEPTABLE;
  932:   } else {
  933:       $targetdir=$docroot.'/res/'.$cudom;
  934:   }
  935:                                  
  936:   
  937:   unless (-e $fn) { 
  938:      $r->log_reason($cuname.' at '.$cudom.
  939:          ' trying to publish non-existing file '.$ENV{'form.filename'}.
  940:          ' ('.$fn.')', 
  941:          $r->filename); 
  942:      return HTTP_NOT_FOUND;
  943:   } 
  944: 
  945: unless ($ENV{'form.phase'} eq 'two') {
  946: 
  947: # --------------------------------- File is there and owned, init lookup tables
  948: 
  949:   %addid=();
  950: 
  951:   {
  952:       my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
  953:       while (<$fh>=~/(\w+)\s+(\w+)/) {
  954:           $addid{$1}=$2;
  955:       }
  956:   }
  957: 
  958:   %nokey=();
  959: 
  960:   {
  961:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
  962:       map {
  963:           my $word=$_;
  964:           chomp($word);
  965:           $nokey{$word}=1;
  966:       } <$fh>;
  967:   }
  968: 
  969:   %language=();
  970: 
  971:   {
  972:      my $fh=Apache::File->new($r->dir_config('lonTabDir').'/language.tab');
  973:       map {
  974:           $_=~/(\w+)\s+([\w\s\-]+)/;
  975:           $language{$1}=$2;
  976:       } <$fh>;
  977:   }
  978: 
  979:   %cprtag=();
  980: 
  981:   {
  982:      my $fh=Apache::File->new($r->dir_config('lonIncludes').'/copyright.tab');
  983:       map {
  984:           $_=~/(\w+)\s+([\w\s\-]+)/;
  985:           $cprtag{$1}=$2;
  986:       } <$fh>;
  987:   }
  988: 
  989: }
  990: 
  991: # ----------------------------------------------------------- Start page output
  992: 
  993:   $r->content_type('text/html');
  994:   $r->send_http_header;
  995: 
  996:   $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
  997:   $r->print(
  998:    '<body bgcolor="#FFFFFF"><img align=right src=/adm/lonIcons/lonlogos.gif>');
  999:   my $thisfn=$fn;
 1000:    
 1001: # ------------------------------------------------------------- Individual file
 1002:   {
 1003:       $thisfn=~/\.(\w+)$/;
 1004:       my $thistype=$1;
 1005:       my $thisembstyle=&Apache::lonnet::fileembstyle($thistype);
 1006: 
 1007:       my $thistarget=$thisfn;
 1008:       
 1009:       $thistarget=~s/^\/home/$targetdir/;
 1010:       $thistarget=~s/\/public\_html//;
 1011: 
 1012:       my $thisdistarget=$thistarget;
 1013:       $thisdistarget=~s/^$docroot//;
 1014: 
 1015:       my $thisdisfn=$thisfn;
 1016:       $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
 1017: 
 1018:       $r->print('<h2>Publishing '.
 1019:         &Apache::lonnet::filedescription($thistype).' <tt>'.
 1020:         $thisdisfn.'</tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
 1021:    
 1022:        if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
 1023:           $r->print('<h3><font color=red>Co-Author: '.$cuname.' at '.$cudom.
 1024:                '</font></h3>');
 1025:       }
 1026: 
 1027:       if (&Apache::lonnet::fileembstyle($thistype) eq 'ssi') {
 1028:           $r->print('<br><a href="/adm/diff?filename=/~'.$cuname.'/'.
 1029:                     $thisdisfn.
 1030:   	  '&versionone=priv" target=cat>Diffs with Current Version</a><p>');
 1031:       }
 1032:   
 1033: # ------------ We are publishing from $thisfn to $thistarget with $thisembstyle
 1034: 
 1035:        unless ($ENV{'form.phase'} eq 'two') {
 1036:          $r->print(
 1037:           '<hr>'.&publish($thisfn,$thistarget,$thisembstyle));
 1038:        } else {
 1039:          $r->print(
 1040:           '<hr>'.&phasetwo($thisfn,$thistarget,$thisembstyle,$thisdistarget)); 
 1041:        }  
 1042: 
 1043:   }
 1044:   $r->print('</body></html>');
 1045: 
 1046:   return OK;
 1047: }
 1048: 
 1049: 1;
 1050: __END__
 1051: 
 1052: 
 1053: 
 1054: 
 1055: 
 1056: 
 1057: 

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