File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.36: download - view: text, annotated - select for diffs
Sat Aug 11 19:06:54 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Deal with <allow>

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

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