File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.30: download - view: text, annotated - select for diffs
Mon May 28 19:43:47 2001 UTC (22 years, 11 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
adding in change date at top

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

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