home *** CD-ROM | disk | FTP | other *** search
/ ftp.f-secure.com / 2014.06.ftp.f-secure.com.tar / ftp.f-secure.com / support / hotfix / fsis / IS-SpamControl.fsfix / iufssc / lib / Mail / SpamAssassin / BayesStore / MySQL.pm < prev    next >
Text File  |  2006-11-29  |  27KB  |  1,043 lines

  1. # <@LICENSE>
  2. # Licensed to the Apache Software Foundation (ASF) under one or more
  3. # contributor license agreements.  See the NOTICE file distributed with
  4. # this work for additional information regarding copyright ownership.
  5. # The ASF licenses this file to you under the Apache License, Version 2.0
  6. # (the "License"); you may not use this file except in compliance with
  7. # the License.  You may obtain a copy of the License at:
  8. #     http://www.apache.org/licenses/LICENSE-2.0
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # </@LICENSE>
  15.  
  16. =head1 NAME
  17.  
  18. Mail::SpamAssassin::BayesStore::MySQL - MySQL Specific Bayesian Storage Module Implementation
  19.  
  20. =head1 SYNOPSIS
  21.  
  22. =head1 DESCRIPTION
  23.  
  24. This module implements a MySQL specific based bayesian storage module.  It
  25. requires that you are running at least version 4.1 of MySQL, if you are running
  26. a version of MySQL < 4.1 then several aspects of this module will fail and
  27. possibly corrupt your bayes database data.
  28.  
  29. In addition, this module will support rollback on error, if you are
  30. using the InnoDB database table type in MySQL.  For more information
  31. please review the instructions in sql/README.bayes.
  32.  
  33. =cut
  34.  
  35. package Mail::SpamAssassin::BayesStore::MySQL;
  36.  
  37. use strict;
  38. use warnings;
  39. use bytes;
  40.  
  41. use Mail::SpamAssassin::BayesStore::SQL;
  42. use Mail::SpamAssassin::Logger;
  43.  
  44. use vars qw( @ISA );
  45.  
  46. @ISA = qw( Mail::SpamAssassin::BayesStore::SQL );
  47.  
  48. use constant HAS_DBI => eval { require DBI; };
  49.  
  50. =head1 METHODS
  51.  
  52. =head2 token_expiration
  53.  
  54. public instance (Integer, Integer,
  55.                  Integer, Integer) token_expiration(\% $opts,
  56.                                                     Integer $newdelta,
  57.                                                     @ @vars)
  58.  
  59. Description:
  60. This method performs the database specific expiration of tokens based on
  61. the passed in C<$newdelta> and C<@vars>.
  62.  
  63. =cut
  64.  
  65. sub token_expiration {
  66.   my ($self, $opts, $newdelta, @vars) = @_;
  67.  
  68.   my $num_hapaxes;
  69.   my $num_lowfreq;
  70.   my $deleted;
  71.  
  72.   # Figure out how old is too old...
  73.   my $too_old = $vars[10] - $newdelta; # tooold = newest - delta
  74.  
  75.   # if token atime > newest, reset to newest ...
  76.   my $sql = "UPDATE bayes_token SET atime = ?
  77.               WHERE id  = ?
  78.                 AND atime > ?";
  79.  
  80.   my $rows = $self->{_dbh}->do($sql, undef, $vars[10], $self->{_userid}, $vars[10]);
  81.  
  82.   unless (defined($rows)) {
  83.     dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
  84.     $deleted = 0;
  85.     $self->{_dbh}->rollback();
  86.     goto token_expiration_final;
  87.   }
  88.  
  89.   # Check to make sure the expire won't remove too many tokens
  90.   $sql = "SELECT count(token) FROM bayes_token
  91.            WHERE id = ?
  92.              AND atime < ?";
  93.  
  94.   my $sth = $self->{_dbh}->prepare_cached($sql);
  95.  
  96.   unless (defined($sth)) {
  97.     dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
  98.     $deleted = 0;
  99.     $self->{_dbh}->rollback();
  100.     goto token_expiration_final;
  101.   }
  102.  
  103.   my $rc = $sth->execute($self->{_userid}, $too_old);
  104.   
  105.   unless ($rc) {
  106.     dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
  107.     $deleted = 0;
  108.     $self->{_dbh}->rollback();
  109.     goto token_expiration_final;
  110.   }
  111.  
  112.   my ($count) = $sth->fetchrow_array();
  113.  
  114.   $sth->finish();
  115.  
  116.   # Sanity check: if we expired too many tokens, abort!
  117.   if ($vars[3] - $count < 100000) {
  118.     dbg("bayes: token expiration would expire too many tokens, aborting");
  119.     # set these appropriately so the next expire pass does the first pass
  120.     $deleted = 0;
  121.     $newdelta = 0;
  122.   }
  123.   else {
  124.     # Do the expire
  125.     $sql = "DELETE from bayes_token
  126.              WHERE id = ?
  127.                AND atime < ?";
  128.  
  129.     $rows = $self->{_dbh}->do($sql, undef, $self->{_userid}, $too_old);
  130.  
  131.     unless (defined($rows)) {
  132.       dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
  133.       $deleted = 0;
  134.       $self->{_dbh}->rollback();
  135.       goto token_expiration_final;
  136.     }
  137.  
  138.     $deleted = $rows;
  139.   }
  140.  
  141.   # Update the magic tokens as appropriate
  142.   $sql = "UPDATE bayes_vars SET token_count = token_count - ?,
  143.                                 last_expire = ?,
  144.                                 last_atime_delta = ?,
  145.                                 last_expire_reduce = ?,
  146.                                 oldest_token_age = (SELECT min(atime)
  147.                                                       FROM bayes_token
  148.                                                      WHERE id = ?)
  149.                 WHERE id = ?";
  150.  
  151.   $rows = $self->{_dbh}->do($sql, undef, $deleted, time(), $newdelta, $deleted, $self->{_userid}, $self->{_userid});
  152.  
  153.   unless (defined($rows)) {
  154.     # Very bad, we actually deleted the tokens, but were unable to update
  155.     # bayes_vars with the new data.
  156.     dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
  157.     $self->{_dbh}->rollback();
  158.     $deleted = 0;
  159.     goto token_expiration_final;
  160.   }
  161.  
  162.   $self->{_dbh}->commit();
  163.  
  164. token_expiration_final:
  165.   my $kept = $vars[3] - $deleted;
  166.  
  167.   $num_hapaxes = $self->_get_num_hapaxes() if ($opts->{verbose});
  168.   $num_lowfreq = $self->_get_num_lowfreq() if ($opts->{verbose});
  169.  
  170.   # Call untie_db() first so we unlock correctly etc. first
  171.   $self->untie_db();
  172.  
  173.   return ($kept, $deleted, $num_hapaxes, $num_lowfreq);
  174. }
  175.  
  176. =head2 seen_put
  177.  
  178. public (Boolean) seen_put (string $msgid, char $flag)
  179.  
  180. Description:
  181. This method records C<$msgid> as the type given by C<$flag>.  C<$flag> is one of
  182. two values 's' for spam and 'h' for ham.
  183.  
  184. =cut
  185.  
  186. sub seen_put {
  187.   my ($self, $msgid, $flag) = @_;
  188.  
  189.   return 0 if (!$msgid);
  190.   return 0 if (!$flag);
  191.   
  192.   return 0 unless (defined($self->{_dbh}));
  193.  
  194.   my $sql = "INSERT INTO bayes_seen (id, msgid, flag)
  195.              VALUES (?,?,?)";
  196.   
  197.   my $rows = $self->{_dbh}->do($sql,
  198.                    undef,
  199.                    $self->{_userid}, $msgid, $flag);
  200.   
  201.   unless (defined($rows)) {
  202.     dbg("bayes: seen_put: SQL error: ".$self->{_dbh}->errstr());
  203.     $self->{_dbh}->rollback();
  204.     return 0;
  205.   }
  206.  
  207.   dbg("bayes: seen ($msgid) put");
  208.   $self->{_dbh}->commit();
  209.   return 1;
  210. }
  211.  
  212. =head2 seen_delete
  213.  
  214. public instance (Boolean) seen_delete (string $msgid)
  215.  
  216. Description:
  217. This method removes C<$msgid> from the database.
  218.  
  219. =cut
  220.  
  221. sub seen_delete {
  222.   my ($self, $msgid) = @_;
  223.  
  224.   return 0 if (!$msgid);
  225.  
  226.   return 0 unless (defined($self->{_dbh}));
  227.  
  228.   my $sql = "DELETE FROM bayes_seen
  229.               WHERE id = ?
  230.                 AND msgid = ?";
  231.   
  232.   my $rows = $self->{_dbh}->do($sql,
  233.                    undef,
  234.                    $self->{_userid}, $msgid);
  235.  
  236.   unless (defined($rows)) {
  237.     dbg("bayes: seen_delete: SQL error: ".$self->{_dbh}->errstr());
  238.     $self->{_dbh}->rollback();
  239.     return 0;
  240.   }
  241.  
  242.   $self->{_dbh}->commit();
  243.   return 1;
  244. }
  245.  
  246. =head2 set_last_expire
  247.  
  248. public instance (Boolean) set_last_expire (Integer $time)
  249.  
  250. Description:
  251. This method sets the last expire time.
  252.  
  253. =cut
  254.  
  255. sub set_last_expire {
  256.   my ($self, $time) = @_;
  257.  
  258.   return 0 unless (defined($time));
  259.  
  260.   return 0 unless (defined($self->{_dbh}));
  261.  
  262.   my $sql = "UPDATE bayes_vars SET last_expire = ? WHERE id = ?";
  263.  
  264.   my $rows = $self->{_dbh}->do($sql,
  265.                    undef,
  266.                    $time,
  267.                    $self->{_userid});
  268.  
  269.   unless (defined($rows)) {
  270.     dbg("bayes: set_last_expire: SQL error: ".$self->{_dbh}->errstr());
  271.     $self->{_dbh}->rollback();
  272.     return 0;
  273.   }
  274.  
  275.   $self->{_dbh}->commit();
  276.   return 1;
  277. }
  278.  
  279. =head2 set_running_expire_tok
  280.  
  281. public instance (String $time) set_running_expire_tok ()
  282.  
  283. Description:
  284. This method sets the time that an expire starts running.
  285.  
  286. =cut
  287.  
  288. sub set_running_expire_tok {
  289.   my ($self) = @_;
  290.  
  291.   return 0 unless (defined($self->{_dbh}));
  292.  
  293.   my $sql = "INSERT INTO bayes_expire (id,runtime) VALUES (?,?)";
  294.  
  295.   my $time = time();
  296.  
  297.   my $rows = $self->{_dbh}->do($sql,
  298.                    undef,
  299.                    $self->{_userid}, $time);
  300.   unless (defined($rows)) {
  301.     dbg("bayes: set_running_expire_tok: SQL error: ".$self->{_dbh}->errstr());
  302.     $self->{_dbh}->rollback();
  303.     return undef;
  304.   }
  305.  
  306.   $self->{_dbh}->commit();
  307.   return $time;
  308. }
  309.  
  310. =head2 remove_running_expire_tok
  311.  
  312. public instance (Boolean) remove_running_expire_tok ()
  313.  
  314. Description:
  315. This method removes the row in the database that indicates that
  316. and expire is currently running.
  317.  
  318. =cut
  319.  
  320. sub remove_running_expire_tok {
  321.   my ($self) = @_;
  322.  
  323.   return 0 unless (defined($self->{_dbh}));
  324.  
  325.   my $sql = "DELETE from bayes_expire
  326.               WHERE id = ?";
  327.  
  328.   my $rows = $self->{_dbh}->do($sql, undef, $self->{_userid});
  329.  
  330.   unless (defined($rows)) {
  331.     dbg("bayes: remove_running_expire_tok: SQL error: ".$self->{_dbh}->errstr());
  332.     $self->{_dbh}->rollback();
  333.     return 0;
  334.   }
  335.  
  336.   $self->{_dbh}->commit();
  337.   return 1;
  338. }
  339.  
  340. =head2 nspam_nham_change
  341.  
  342. public instance (Boolean) nspam_nham_change (Integer $num_spam,
  343.                                              Integer $num_ham)
  344.  
  345. Description:
  346. This method updates the number of spam and the number of ham in the database.
  347.  
  348. =cut
  349.  
  350. sub nspam_nham_change {
  351.   my ($self, $num_spam, $num_ham) = @_;
  352.  
  353.   return 0 unless (defined($self->{_dbh}));
  354.  
  355.   my $sql;
  356.   my @bindings;
  357.  
  358.   if ($num_spam != 0 && $num_ham != 0) {
  359.     $sql = "UPDATE bayes_vars
  360.                SET spam_count = spam_count + ?,
  361.                    ham_count = ham_count + ?
  362.              WHERE id = ?";
  363.     @bindings = ($num_spam, $num_ham, $self->{_userid});
  364.   }
  365.   elsif ($num_spam != 0) {
  366.     $sql = "UPDATE bayes_vars
  367.               SET spam_count = spam_count + ?
  368.              WHERE id = ?";
  369.     @bindings = ($num_spam, $self->{_userid});
  370.   }
  371.   elsif ($num_ham != 0) {
  372.     $sql = "UPDATE bayes_vars
  373.                SET ham_count = ham_count + ?
  374.             WHERE id = ?";
  375.     @bindings = ($num_ham, $self->{_userid});
  376.   }
  377.   else {
  378.     # For some reason called with no delta, it's ok though so just return
  379.     dbg("bayes: nspam_nham_change: Called with no delta on spam or ham");
  380.     return 1;
  381.   }
  382.  
  383.   my $rows = $self->{_dbh}->do($sql,
  384.                    undef,
  385.                    @bindings);
  386.  
  387.   unless (defined($rows)) {
  388.     dbg("bayes: nspam_nham_change: SQL error: ".$self->{_dbh}->errstr());
  389.     $self->{_dbh}->rollback();
  390.     return 0;
  391.   }
  392.  
  393.   $self->{_dbh}->commit();
  394.   return 1;
  395. }
  396.  
  397. =head2 tok_touch
  398.  
  399. public instance (Boolean) tok_touch (String $token,
  400.                                      String $atime)
  401.  
  402. Description:
  403. This method updates the given tokens (C<$token>) atime.
  404.  
  405. The assumption is that the token already exists in the database.
  406.  
  407. =cut
  408.  
  409. sub tok_touch {
  410.   my ($self, $token, $atime) = @_;
  411.  
  412.   return 0 unless (defined($self->{_dbh}));
  413.  
  414.   # shortcut, will only update atime for the token if the atime is less than
  415.   # what we are updating to
  416.   my $sql = "UPDATE bayes_token
  417.                 SET atime = ?
  418.               WHERE id = ?
  419.                 AND token = ?
  420.                 AND atime < ?";
  421.  
  422.   my $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid},
  423.                    $token, $atime);
  424.  
  425.   unless (defined($rows)) {
  426.     dbg("bayes: tok_touch: SQL error: ".$self->{_dbh}->errstr());
  427.     $self->{_dbh}->rollback();
  428.     return 0;
  429.   }
  430.  
  431.   # if we didn't update a row then no need to update newest_token_age
  432.   return 1 if ($rows eq '0E0');
  433.  
  434.   # need to check newest_token_age
  435.   # no need to check oldest_token_age since we would only update if the
  436.   # atime was newer than what is in the database
  437.   $sql = "UPDATE bayes_vars
  438.              SET newest_token_age = ?
  439.            WHERE id = ?
  440.              AND newest_token_age < ?";
  441.  
  442.   $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
  443.  
  444.   unless (defined($rows)) {
  445.     dbg("bayes: tok_touch: SQL error: ".$self->{_dbh}->errstr());
  446.     $self->{_dbh}->rollback();
  447.     return 0;
  448.   }
  449.  
  450.   $self->{_dbh}->commit();
  451.   return 1;
  452. }
  453.  
  454. =head2 tok_touch_all
  455.  
  456. public instance (Boolean) tok_touch (\@ $tokens
  457.                                      String $atime)
  458.  
  459. Description:
  460. This method does a mass update of the given list of tokens C<$tokens>, if the existing token
  461. atime is < C<$atime>.
  462.  
  463. The assumption is that the tokens already exist in the database.
  464.  
  465. We should never be touching more than N_SIGNIFICANT_TOKENS, so we can make
  466. some assumptions about how to handle the data (ie no need to batch like we
  467. do in tok_get_all)
  468.  
  469. =cut
  470.  
  471. sub tok_touch_all {
  472.   my ($self, $tokens, $atime) = @_;
  473.  
  474.   return 0 unless (defined($self->{_dbh}));
  475.  
  476.   return 1 unless (scalar(@{$tokens}));
  477.  
  478.   my $sql = "UPDATE bayes_token SET atime = ? WHERE id = ? AND token IN (";
  479.  
  480.   my @bindings = ($atime, $self->{_userid});
  481.   foreach my $token (@{$tokens}) {
  482.     $sql .= "?,";
  483.     push(@bindings, $token);
  484.   }
  485.   chop($sql); # get rid of trailing ,
  486.  
  487.   $sql .= ") AND atime < ?";
  488.   push(@bindings, $atime);
  489.  
  490.   my $rows = $self->{_dbh}->do($sql, undef, @bindings);
  491.  
  492.   unless (defined($rows)) {
  493.     dbg("bayes: tok_touch_all: SQL error: ".$self->{_dbh}->errstr());
  494.     $self->{_dbh}->rollback();
  495.     return 0;
  496.   }
  497.  
  498.   # if we didn't update a row then no need to update newest_token_age
  499.   return 1 if ($rows eq '0E0');
  500.  
  501.   # need to check newest_token_age
  502.   # no need to check oldest_token_age since we would only update if the
  503.   # atime was newer than what is in the database
  504.   $sql = "UPDATE bayes_vars
  505.              SET newest_token_age = ?
  506.            WHERE id = ?
  507.              AND newest_token_age < ?";
  508.  
  509.   $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
  510.  
  511.   unless (defined($rows)) {
  512.     dbg("bayes: tok_touch_all: SQL error: ".$self->{_dbh}->errstr());
  513.     $self->{_dbh}->rollback();
  514.     return 0;
  515.   }
  516.  
  517.   $self->{_dbh}->commit();
  518.   return 1;
  519. }
  520.  
  521. =head2 cleanup
  522.  
  523. public instance (Boolean) cleanup ()
  524.  
  525. Description:
  526. This method peroms any cleanup necessary before moving onto the next
  527. operation.
  528.  
  529. =cut
  530.  
  531. sub cleanup {
  532.   my ($self) = @_;
  533.  
  534.   return 1 unless ($self->{needs_cleanup});
  535.  
  536.   # cleanup was needed, go ahead and clear the cleanup flag
  537.   $self->{needs_cleanup} = 0;
  538.  
  539.   my $sql = "DELETE from bayes_token
  540.               WHERE id = ?
  541.                 AND spam_count <= 0
  542.                 AND ham_count <= 0";
  543.  
  544.   my $toks_deleted = $self->{_dbh}->do($sql, undef, $self->{_userid});
  545.  
  546.   unless (defined($toks_deleted)) {
  547.     dbg("bayes: cleanup: SQL error: ".$self->{_dbh}->errstr());
  548.     $self->{_dbh}->rollback();
  549.     return 0;
  550.   }       
  551.  
  552.   # check to see if any tokens where deleted
  553.   return 1 if ($toks_deleted eq '0E0');
  554.  
  555.   $sql = "UPDATE bayes_vars SET token_count = token_count - ? WHERE id = ?";
  556.  
  557.   my $rows = $self->{_dbh}->do($sql, undef, $toks_deleted, $self->{_userid});
  558.  
  559.   unless (defined($rows)) {
  560.     dbg("bayes: cleanup: SQL error: ".$self->{_dbh}->errstr());
  561.     $self->{_dbh}->rollback();
  562.     return 0;
  563.   }       
  564.  
  565.   $self->{_dbh}->commit();
  566.   return 1;
  567. }
  568.  
  569. =head2 clear_database
  570.  
  571. public instance (Boolean) clear_database ()
  572.  
  573. Description:
  574. This method deletes all records for a particular user.
  575.  
  576. Callers should be aware that any errors returned by this method
  577. could causes the database to be inconsistent for the given user.
  578.  
  579. =cut
  580.  
  581. sub clear_database {
  582.   my ($self) = @_;
  583.  
  584.   # We want to open readonly first, because if they don't already have
  585.   # a db entry, we want to avoid creating one, just to delete it in a few secs
  586.   if ($self->tie_db_readonly()) {
  587.     # Ok, they must have had a db entry, so now make the connection writable
  588.     $self->tie_db_writable();
  589.   }
  590.   else {
  591.     # If we were unable to create a readonly connection then they must
  592.     # not have a db entry, so no need to clear.
  593.     # But it should be considered a success.
  594.     return 1;
  595.   }
  596.  
  597.   return 0 unless (defined($self->{_dbh}));
  598.  
  599.   my $rows = $self->{_dbh}->do("DELETE FROM bayes_vars WHERE id = ?",
  600.                    undef,
  601.                    $self->{_userid});
  602.   unless (defined($rows)) {
  603.     dbg("bayes: SQL error removing user (bayes_vars) data: ".$self->{_dbh}->errstr());
  604.     $self->{_dbh}->rollback();
  605.     return 0;
  606.   }
  607.  
  608.   $rows = $self->{_dbh}->do("DELETE FROM bayes_seen WHERE id = ?",
  609.                 undef,
  610.                 $self->{_userid});
  611.   unless (defined($rows)) {
  612.     dbg("bayes: SQL error removing seen data: ".$self->{_dbh}->errstr());
  613.     $self->{_dbh}->rollback();
  614.     return 0;
  615.   }
  616.  
  617.   $rows = $self->{_dbh}->do("DELETE FROM bayes_token WHERE id = ?",
  618.                 undef,
  619.                 $self->{_userid});
  620.   unless (defined($rows)) {
  621.     dbg("bayes: SQL error removing token data: ".$self->{_dbh}->errstr());
  622.     $self->{_dbh}->rollback();
  623.     return 0;
  624.   }
  625.  
  626.   $self->{_dbh}->commit();
  627.   return 1;
  628. }
  629.  
  630. =head1 Private Methods
  631.  
  632. =head2 _connect_db
  633.  
  634. private instance (Boolean) _connect_db ()
  635.  
  636. Description:
  637. This method connects to the SQL database.
  638.  
  639. =cut
  640.  
  641. sub _connect_db {
  642.   my ($self) = @_;
  643.  
  644.   $self->{_dbh} = undef;
  645.  
  646.   # Turn off PrintError and explicitly set AutoCommit to off
  647.   my $dbh = DBI->connect($self->{_dsn}, $self->{_dbuser}, $self->{_dbpass},
  648.                         {'PrintError' => 0, 'AutoCommit' => 0});
  649.  
  650.   if (!$dbh) {
  651.     dbg("bayes: unable to connect to database: ".DBI->errstr());
  652.     return 0;
  653.   }
  654.   else {
  655.     dbg("bayes: database connection established");
  656.   }
  657.  
  658.   $self->{_dbh} = $dbh;
  659.  
  660.  return 1;
  661. }
  662.  
  663. =head2 _initialize_db
  664.  
  665. private instance (Boolean) _initialize_db ()
  666.  
  667. Description:
  668. This method will check to see if a user has had their bayes variables
  669. initialized. If not then it will perform this initialization.
  670.  
  671. =cut
  672.  
  673. sub _initialize_db {
  674.   my ($self, $create_entry_p) = @_;
  675.  
  676.   return 0 unless (defined($self->{_dbh}));
  677.  
  678.   return 0 if (!$self->{_username});
  679.  
  680.   # Check to see if we should call the services_authorized_for_username plugin
  681.   # hook to see if this user is allowed/able to use bayes.  If not, do nothing
  682.   # and return 0.
  683.   if ($self->{bayes}->{conf}->{bayes_sql_username_authorized}) {
  684.     my $services = { 'bayessql' => 0 };
  685.     $self->{bayes}->{main}->call_plugins("services_allowed_for_username",
  686.                      { services => $services,
  687.                        username => $self->{_username},
  688.                        conf => $self->{bayes}->{conf},
  689.                      });
  690.     
  691.     unless ($services->{bayessql}) {
  692.       dbg("bayes: username not allowed by services_allowed_for_username plugin call");
  693.       return 0;
  694.     }
  695.   }
  696.  
  697.   my $sqlselect = "SELECT id FROM bayes_vars WHERE username = ?";
  698.  
  699.   my $sthselect = $self->{_dbh}->prepare_cached($sqlselect);
  700.  
  701.   unless (defined($sthselect)) {
  702.     dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
  703.     return 0;
  704.   }
  705.  
  706.   my $rc = $sthselect->execute($self->{_username});
  707.  
  708.   unless ($rc) {
  709.     dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
  710.     return 0;
  711.   }
  712.  
  713.   my ($id) = $sthselect->fetchrow_array();
  714.  
  715.   if ($id) {
  716.     $self->{_userid} = $id;
  717.     dbg("bayes: Using userid: ".$self->{_userid});
  718.     $sthselect->finish();
  719.     return 1;
  720.   }
  721.  
  722.   # Do not create an entry for this user unless we were specifically asked to
  723.   return 0 unless ($create_entry_p);
  724.  
  725.   # For now let the database setup the other variables as defaults
  726.   my $sqlinsert = "INSERT INTO bayes_vars (username) VALUES (?)";
  727.  
  728.   my $rows = $self->{_dbh}->do($sqlinsert,
  729.                    undef,
  730.                    $self->{_username});
  731.   unless (defined($rows)) {
  732.     dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
  733.     $self->{_dbh}->rollback();
  734.     return 0;
  735.   }
  736.  
  737.   $id = $self->{_dbh}->{'mysql_insertid'};
  738.  
  739.   $self->{_dbh}->commit();
  740.  
  741.   if ($id) {
  742.     $self->{_userid} = $id;
  743.     dbg("bayes: using userid: ".$self->{_userid});
  744.     return 1;
  745.   }
  746.  
  747.   return 1;
  748. }
  749.  
  750. =head2 _put_token
  751.  
  752. private instance (Boolean) _put_token (string $token,
  753.                                        integer $spam_count,
  754.                                        integer $ham_count,
  755.                        string $atime)
  756.  
  757. Description:
  758. This method performs the work of either inserting or updating a token in
  759. the database.
  760.  
  761. =cut
  762.  
  763. sub _put_token {
  764.   my ($self, $token, $spam_count, $ham_count, $atime) = @_;
  765.  
  766.   return 0 unless (defined($self->{_dbh}));
  767.  
  768.   $spam_count ||= 0;
  769.   $ham_count ||= 0;
  770.  
  771.   if ($spam_count == 0 && $ham_count == 0) {
  772.     return 1;
  773.   }
  774.  
  775.   # the case where spam_count of ham_count is < 0 is special, it assumes
  776.   # that there already exists a token (although there might actually not be
  777.   # be one) that will be updated.  So we just do the update, being careful
  778.   # to not allow the spam_count or ham_count to not drop below 0
  779.   # In addition, when lowering the spam_count or ham_count we will not be
  780.   # updating the atime value
  781.   if ($spam_count < 0 || $ham_count < 0) {
  782.     # we only need to cleanup when we subtract counts for a token and the
  783.     # counts may have both reached 0
  784.     $self->{needs_cleanup} = 1;
  785.  
  786.     my $sql = "UPDATE bayes_token SET spam_count = GREATEST(spam_count + ?, 0),
  787.                                       ham_count = GREATEST(ham_count + ?, 0)
  788.                 WHERE id = ?
  789.                   AND token = ?";
  790.  
  791.     my $sth = $self->{_dbh}->prepare_cached($sql);
  792.  
  793.     unless (defined($sth)) {
  794.       dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
  795.       $self->{_dbh}->rollback();
  796.       return 0;
  797.     }
  798.  
  799.     my $rc = $sth->execute($spam_count,
  800.                $ham_count,
  801.                $self->{_userid},
  802.                $token);
  803.  
  804.     unless ($rc) {
  805.       dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
  806.       $self->{_dbh}->rollback();
  807.       return 0;
  808.     }
  809.   }
  810.   else {
  811.     my $sql = "INSERT INTO bayes_token
  812.                (id, token, spam_count, ham_count, atime)
  813.                VALUES (?,?,?,?,?)
  814.                ON DUPLICATE KEY UPDATE spam_count = GREATEST(spam_count + ?, 0),
  815.                                        ham_count = GREATEST(ham_count + ?, 0),
  816.                                        atime = GREATEST(atime, ?)";
  817.  
  818.     my $sth = $self->{_dbh}->prepare_cached($sql);
  819.  
  820.     unless (defined($sth)) {
  821.       dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
  822.       $self->{_dbh}->rollback();
  823.       return 0;
  824.     }
  825.  
  826.     my $rc = $sth->execute($self->{_userid},
  827.                $token,
  828.                $spam_count,
  829.                $ham_count,
  830.                $atime,
  831.                $spam_count,
  832.                $ham_count,
  833.                $atime);
  834.  
  835.     unless ($rc) {
  836.       dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
  837.       $self->{_dbh}->rollback();
  838.       return 0;
  839.     }
  840.  
  841.     my $num_rows = $rc;
  842.  
  843.     $sth->finish();
  844.  
  845.     if ($num_rows == 1 || $num_rows == 2) {
  846.       my $token_count_update = '';
  847.       
  848.       $token_count_update = "token_count = token_count + 1," if ($num_rows == 1);
  849.       $sql = "UPDATE bayes_vars SET
  850.                      $token_count_update
  851.                      newest_token_age = GREATEST(newest_token_age, ?),
  852.                      oldest_token_age = LEAST(oldest_token_age, ?)
  853.                WHERE id = ?";
  854.  
  855.       $sth = $self->{_dbh}->prepare_cached($sql);
  856.  
  857.       unless (defined($sth)) {
  858.     dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
  859.     $self->{_dbh}->rollback();
  860.     return 0;
  861.       }
  862.  
  863.       my $rc = $sth->execute($atime, $atime, $self->{_userid});
  864.  
  865.       unless ($rc) {
  866.     dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
  867.     $self->{_dbh}->rollback();
  868.     return 0;
  869.       }
  870.     }
  871.     else {
  872.       # $num_rows was not what we expected
  873.       dbg("bayes: _put_token: Updated an unexpected number of rows.");
  874.       $self->{_dbh}->rollback();
  875.       return 0;
  876.     }
  877.   }
  878.  
  879.   $self->{_dbh}->commit();
  880.   return 1;
  881. }
  882.  
  883. =head2 _put_tokens
  884.  
  885. private instance (Boolean) _put_tokens (\% $tokens,
  886.                                         integer $spam_count,
  887.                                         integer $ham_count,
  888.                          string $atime)
  889.  
  890. Description:
  891. This method performs the work of either inserting or updating tokens in
  892. the database.
  893.  
  894. =cut
  895.  
  896. sub _put_tokens {
  897.   my ($self, $tokens, $spam_count, $ham_count, $atime) = @_;
  898.  
  899.   return 0 unless (defined($self->{_dbh}));
  900.  
  901.   $spam_count ||= 0;
  902.   $ham_count ||= 0;
  903.  
  904.   if ($spam_count == 0 && $ham_count == 0) {
  905.     return 1;
  906.   }
  907.  
  908.   # the case where spam_count of ham_count is < 0 is special, it assumes
  909.   # that there already exists a token (although there might actually not be
  910.   # be one) that will be updated.  So we just do the update, being careful
  911.   # to not allow the spam_count or ham_count to not drop below 0
  912.   # In addition, when lowering the spam_count or ham_count we will not be
  913.   # updating the atime value
  914.   if ($spam_count < 0 || $ham_count < 0) {
  915.     # we only need to cleanup when we subtract counts for a token and the
  916.     # counts may have both reached 0
  917.     $self->{needs_cleanup} = 1;
  918.  
  919.     my $sql = "UPDATE bayes_token SET spam_count = GREATEST(spam_count + ?, 0),
  920.                                       ham_count = GREATEST(ham_count + ?, 0)
  921.                 WHERE id = ?
  922.                   AND token = ?";
  923.  
  924.     my $sth = $self->{_dbh}->prepare_cached($sql);
  925.  
  926.     unless (defined($sth)) {
  927.       dbg("bayes: _put_tokens: SQL error: ".$self->{_dbh}->errstr());
  928.       $self->{_dbh}->rollback();
  929.       return 0;
  930.     }
  931.  
  932.     my $error_p = 0;
  933.     foreach my $token (keys %{$tokens}) {
  934.       my $rc = $sth->execute($spam_count,
  935.                  $ham_count,
  936.                  $self->{_userid},
  937.                  $token);
  938.  
  939.       unless ($rc) {
  940.     dbg("bayes: _put_tokens: SQL error: ".$self->{_dbh}->errstr());
  941.     $error_p = 1;
  942.       }
  943.     }
  944.  
  945.     $sth->finish();
  946.  
  947.     if ($error_p) {
  948.       $self->{_dbh}->rollback();
  949.       return 0;
  950.     }
  951.   }
  952.   else {
  953.     my $sql = "INSERT INTO bayes_token
  954.                (id, token, spam_count, ham_count, atime)
  955.                VALUES (?,?,?,?,?)
  956.                ON DUPLICATE KEY UPDATE spam_count = GREATEST(spam_count + ?, 0),
  957.                                        ham_count = GREATEST(ham_count + ?, 0),
  958.                                        atime = GREATEST(atime, ?)";
  959.  
  960.     my $sth = $self->{_dbh}->prepare_cached($sql);
  961.  
  962.     unless (defined($sth)) {
  963.       dbg("bayes: _put_tokens: SQL error: ".$self->{_dbh}->errstr());
  964.       $self->{_dbh}->rollback();
  965.       return 0;
  966.     }
  967.  
  968.     my $error_p = 0;
  969.     my $new_tokens = 0;
  970.     my $need_atime_update_p = 0;
  971.     foreach my $token (keys %{$tokens}) {
  972.       my $rc = $sth->execute($self->{_userid},
  973.                  $token,
  974.                  $spam_count,
  975.                  $ham_count,
  976.                  $atime,
  977.                  $spam_count,
  978.                  $ham_count,
  979.                  $atime);
  980.  
  981.       if (!$rc) {
  982.     dbg("bayes: _put_tokens: SQL error: ".$self->{_dbh}->errstr());
  983.     $error_p = 1;
  984.       }
  985.       else {
  986.     my $num_rows = $rc;
  987.  
  988.     $need_atime_update_p = 1 if ($num_rows == 1 || $num_rows == 2);
  989.     $new_tokens++ if ($num_rows == 1);
  990.       }
  991.     }
  992.  
  993.     $sth->finish();
  994.  
  995.     if ($error_p) {
  996.       $self->{_dbh}->rollback();
  997.       return 0;
  998.     }
  999.  
  1000.     if ($need_atime_update_p) {
  1001.       my $token_count_update = '';
  1002.       
  1003.       $token_count_update = "token_count = token_count + $new_tokens," if ($new_tokens);
  1004.       $sql = "UPDATE bayes_vars SET
  1005.                      $token_count_update
  1006.                      newest_token_age = GREATEST(newest_token_age, ?),
  1007.                      oldest_token_age = LEAST(oldest_token_age, ?)
  1008.                WHERE id = ?";
  1009.  
  1010.       $sth = $self->{_dbh}->prepare_cached($sql);
  1011.  
  1012.       unless (defined($sth)) {
  1013.     dbg("bayes: _put_tokens: SQL error: ".$self->{_dbh}->errstr());
  1014.     $self->{_dbh}->rollback();
  1015.     return 0;
  1016.       }
  1017.  
  1018.       my $rc = $sth->execute($atime, $atime, $self->{_userid});
  1019.  
  1020.       unless ($rc) {
  1021.     dbg("bayes: _put_tokens: SQL error: ".$self->{_dbh}->errstr());
  1022.     $self->{_dbh}->rollback();
  1023.     return 0;
  1024.       }
  1025.     }
  1026.     else {
  1027.       # $num_rows was not what we expected
  1028.       dbg("bayes: _put_tokens: Updated an unexpected number of rows.");
  1029.       $self->{_dbh}->rollback();
  1030.       return 0;
  1031.     }
  1032.   }
  1033.  
  1034.   $self->{_dbh}->commit();
  1035.   return 1;
  1036. }
  1037.  
  1038. sub sa_die { Mail::SpamAssassin::sa_die(@_); }
  1039.  
  1040. 1;
  1041.