File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.25: download - view: text, annotated - select for diffs
Mon Apr 16 20:47:27 2001 UTC (23 years, 1 month ago) by harris41
Branches: MAIN
CVS tags: HEAD
deglobalizing a few variables, calculating sql-formatted date-time strings,
reading in PerlVar's so that the sql database can be accessed.. -Scott

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

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