File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.29: download - view: text, annotated - select for diffs
Mon May 28 19:43:09 2001 UTC (23 years ago) by harris41
Branches: MAIN
CVS tags: HEAD
changing sql database connection to just output a warning
instead of terminating the publication

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

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