File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.34: download - view: text, annotated - select for diffs
Sat Aug 11 18:06:25 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Start on URL cleanup

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

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