File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.45: download - view: text, annotated - select for diffs
Wed Sep 26 16:26:49 2001 UTC (22 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Public publication not an option for maps

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

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