From c8c062d96024a23e67e73f1ebffcf7009b18eed1 Mon Sep 17 00:00:00 2001 From: friendica Date: Tue, 31 Jan 2012 15:54:41 -0800 Subject: [PATCH] add spam engine --- library/spam/b8/b8.php | 503 +++++++++++++ .../b8/degenerator/degenerator_default.php | 127 ++++ library/spam/b8/lexer/lexer_default.php | 205 +++++ library/spam/b8/storage/storage_base.php | 395 ++++++++++ library/spam/b8/storage/storage_dba.php | 198 +++++ library/spam/b8/storage/storage_mysql.php | 351 +++++++++ library/spam/doc/COPYING | 504 +++++++++++++ library/spam/doc/ChangeLog | 179 +++++ library/spam/doc/readme.htm | 707 ++++++++++++++++++ library/spam/doc/readme.rst | 371 +++++++++ library/spam/example/index.php | 241 ++++++ library/spam/install/setup_berkeleydb.php | 240 ++++++ library/spam/install/setup_mysql.sql | 27 + 13 files changed, 4048 insertions(+) create mode 100644 library/spam/b8/b8.php create mode 100644 library/spam/b8/degenerator/degenerator_default.php create mode 100644 library/spam/b8/lexer/lexer_default.php create mode 100644 library/spam/b8/storage/storage_base.php create mode 100644 library/spam/b8/storage/storage_dba.php create mode 100644 library/spam/b8/storage/storage_mysql.php create mode 100644 library/spam/doc/COPYING create mode 100644 library/spam/doc/ChangeLog create mode 100644 library/spam/doc/readme.htm create mode 100644 library/spam/doc/readme.rst create mode 100644 library/spam/example/index.php create mode 100644 library/spam/install/setup_berkeleydb.php create mode 100644 library/spam/install/setup_mysql.sql diff --git a/library/spam/b8/b8.php b/library/spam/b8/b8.php new file mode 100644 index 000000000..ea1e15ffa --- /dev/null +++ b/library/spam/b8/b8.php @@ -0,0 +1,503 @@ + +# +# b8 - A Bayesian spam filter written in PHP 5 +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +/** + * Copyright (C) 2006-2010 Tobias Leupold + * + * @license LGPL + * @access public + * @package b8 + * @author Tobias Leupold + * @author Oliver Lillie (aka buggedcom) (original PHP 5 port) + */ + +class b8 +{ + + public $config = array( + 'min_size' => 3, + 'max_size' => 30, + 'allow_numbers' => FALSE, + 'lexer' => 'default', + 'degenerator' => 'default', + 'storage' => 'dba', + 'use_relevant' => 15, + 'min_dev' => 0.2, + 'rob_s' => 0.3, + 'rob_x' => 0.5 + ); + + private $_lexer = NULL; + private $_database = NULL; + private $_token_data = NULL; + + const SPAM = 'spam'; + const HAM = 'ham'; + const LEARN = 'learn'; + const UNLEARN = 'unlearn'; + + const STARTUP_FAIL_DATABASE = 'STARTUP_FAIL_DATABASE'; + const STARTUP_FAIL_LEXER = 'STARTUP_FAIL_LEXER'; + const TRAINER_CATEGORY_FAIL = 'TRAINER_CATEGORY_FAIL'; + + /** + * Constructs b8 + * + * @access public + * @return void + */ + + function __construct($config = array(), $database_config) + { + + # Validate config data + + if(count($config) > 0) { + + foreach ($config as $name=>$value) { + + switch($name) { + + case 'min_dev': + case 'rob_s': + case 'rob_x': + $this->config[$name] = (float) $value; + break; + + case 'min_size': + case 'max_size': + case 'use_relevant': + $this->config[$name] = (int) $value; + break; + + case 'allow_numbers': + $this->config[$name] = (bool) $value; + break; + + case 'lexer': + $value = (string) strtolower($value); + $this->config[$name] = is_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lexer' . DIRECTORY_SEPARATOR . "lexer_" . $value . '.php') === TRUE ? $value : 'default'; + break; + + case 'storage': + $this->config[$name] = (string) $value; + break; + + } + + } + + } + + # Setup the database backend + + # Get the basic storage class used by all backends + if($this->load_class('b8_storage_base', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'storage_base.php') === FALSE) + return; + + # Get the degenerator we need + if($this->load_class('b8_degenerator_' . $this->config['degenerator'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'degenerator' . DIRECTORY_SEPARATOR . 'degenerator_' . $this->config['degenerator'] . '.php') === FALSE) + return; + + # Get the actual storage backend we need + if($this->load_class('b8_storage_' . $this->config['storage'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'storage_' . $this->config['storage'] . '.php') === FALSE) + return; + + # Setup the backend + $class = 'b8_storage_' . $this->config['storage']; + $this->_database = new $class( + $database_config, + $this->config['degenerator'], date('ymd') + ); + + # Setup the lexer class + + if($this->load_class('b8_lexer_' . $this->config['lexer'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lexer' . DIRECTORY_SEPARATOR . 'lexer_' . $this->config['lexer'] . '.php') === FALSE) + return; + + $class = 'b8_lexer_' . $this->config['lexer']; + $this->_lexer = new $class( + array( + 'min_size' => $this->config['min_size'], + 'max_size' => $this->config['max_size'], + 'allow_numbers' => $this->config['allow_numbers'] + ) + ); + + } + + /** + * Load a class file if a class has not been defined yet. + * + * @access public + * @return boolean Returns TRUE if everything is okay, otherwise FALSE. + */ + + public function load_class($class_name, $class_file) + { + + if(class_exists($class_name, FALSE) === FALSE) { + + $included = require_once $class_file; + + if($included === FALSE or class_exists($class_name, FALSE) === FALSE) + return FALSE; + + } + + return TRUE; + + } + + /** + * Validates the class has all it needs to work. + * + * @access public + * @return mixed Returns TRUE if everything is okay, otherwise an error code. + */ + + public function validate() + { + + if($this->_database === NULL) + return self::STARTUP_FAIL_DATABASE; + + # Connect the database backend if we aren't connected yet + + elseif($this->_database->connected === FALSE) { + + $connection = $this->_database->connect(); + + if($connection !== TRUE) + return $connection; + + } + + if($this->_lexer === NULL) + return self::STARTUP_FAIL_LEXER; + + return TRUE; + + } + + /** + * Classifies a text + * + * @access public + * @package default + * @param string $text + * @return float The rating between 0 (ham) and 1 (spam) + */ + + public function classify($text) + { + + # Validate the startup + + $started_up = $this->validate(); + + if($started_up !== TRUE) + return $started_up; + + # Get the internal database variables, containing the number of ham and + # spam texts so the spam probability can be calculated in relation to them + $internals = $this->_database->get_internals(); + + # Calculate the spamminess of all tokens + + # Get all tokens we want to rate + + $tokens = $this->_lexer->get_tokens($text); + + # Check if the lexer failed + # (if so, $tokens will be a lexer error code, if not, $tokens will be an array) + if(!is_array($tokens)) + return $tokens; + + # Fetch all availible data for the token set from the database + $this->_token_data = $this->_database->get(array_keys($tokens)); + + # Calculate the spamminess and importance for each token (or a degenerated form of it) + + $word_count = array(); + $rating = array(); + $importance = array(); + + foreach($tokens as $word => $count) { + + $word_count[$word] = $count; + + # Although we only call this function only here ... let's do the + # calculation stuff in a function to make this a bit less confusing ;-) + $rating[$word] = $this->_get_probability($word, $internals['texts_ham'], $internals['texts_spam']); + + $importance[$word] = abs(0.5 - $rating[$word]); + + } + + # Order by importance + arsort($importance); + reset($importance); + + # Get the most interesting tokens (use all if we have less than the given number) + + $relevant = array(); + + for($i = 0; $i < $this->config['use_relevant']; $i++) { + + if($tmp = each($importance)) { + + # Important tokens remain + + # If the token's rating is relevant enough, use it + + if(abs(0.5 - $rating[$tmp['key']]) > $this->config['min_dev']) { + + # Tokens that appear more than once also count more than once + + for($x = 0, $l = $word_count[$tmp['key']]; $x < $l; $x++) + array_push($relevant, $rating[$tmp['key']]); + + } + + } + + else { + # We have less than words to use, so we already + # use what we have and can break here + break; + } + + } + + # Calculate the spamminess of the text (thanks to Mr. Robinson ;-) + # We set both hamminess and Spamminess to 1 for the first multiplying + $hamminess = 1; + $spamminess = 1; + + # Consider all relevant ratings + foreach($relevant as $value) { + $hamminess *= (1.0 - $value); + $spamminess *= $value; + } + + # If no token was good for calculation, we really don't know how + # to rate this text; so we assume a spam and ham probability of 0.5 + + if($hamminess === 1 and $spamminess === 1) { + $hamminess = 0.5; + $spamminess = 0.5; + $n = 1; + } + else { + # Get the number of relevant ratings + $n = count($relevant); + } + + # Calculate the combined rating + + # The actual hamminess and spamminess + $hamminess = 1 - pow($hamminess, (1 / $n)); + $spamminess = 1 - pow($spamminess, (1 / $n)); + + # Calculate the combined indicator + $probability = ($hamminess - $spamminess) / ($hamminess + $spamminess); + + # We want a value between 0 and 1, not between -1 and +1, so ... + $probability = (1 + $probability) / 2; + + # Alea iacta est + return $probability; + + } + + /** + * Calculate the spamminess of a single token also considering "degenerated" versions + * + * @access private + * @param string $word + * @param string $texts_ham + * @param string $texts_spam + * @return void + */ + + private function _get_probability($word, $texts_ham, $texts_spam) + { + + # Let's see what we have! + + if(isset($this->_token_data['tokens'][$word]) === TRUE) { + # The token was in the database, so we can use it's data as-is + # and calculate the spamminess of this token directly + return $this->_calc_probability($this->_token_data['tokens'][$word], $texts_ham, $texts_spam); + } + + # Damn. The token was not found, so do we have at least similar words? + + if(isset($this->_token_data['degenerates'][$word]) === TRUE) { + + # We found similar words, so calculate the spamminess for each one + # and choose the most important one for the further calculation + + # The default rating is 0.5 simply saying nothing + $rating = 0.5; + + foreach($this->_token_data['degenerates'][$word] as $degenerate => $count) { + + # Calculate the rating of the current degenerated token + $rating_tmp = $this->_calc_probability($count, $texts_ham, $texts_spam); + + # Is it more important than the rating of another degenerated version? + if(abs(0.5 - $rating_tmp) > abs(0.5 - $rating)) + $rating = $rating_tmp; + + } + + return $rating; + + } + + else { + # The token is really unknown, so choose the default rating + # for completely unknown tokens. This strips down to the + # robX parameter so we can cheap out the freaky math ;-) + return $this->config['rob_x']; + } + + } + + /** + * Do the actual spamminess calculation of a single token + * + * @access private + * @param array $data + * @param string $texts_ham + * @param string $texts_spam + * @return void + */ + + private function _calc_probability($data, $texts_ham, $texts_spam) + { + + # Calculate the basic probability by Mr. Graham + + # But: consider the number of ham and spam texts saved instead of the + # number of entries where the token appeared to calculate a relative + # spamminess because we count tokens appearing multiple times not just + # once but as often as they appear in the learned texts + + $rel_ham = $data['count_ham']; + $rel_spam = $data['count_spam']; + + if($texts_ham > 0) + $rel_ham = $data['count_ham'] / $texts_ham; + + if($texts_spam > 0) + $rel_spam = $data['count_spam'] / $texts_spam; + + $rating = $rel_spam / ($rel_ham + $rel_spam); + + # Calculate the better probability proposed by Mr. Robinson + $all = $data['count_ham'] + $data['count_spam']; + return (($this->config['rob_s'] * $this->config['rob_x']) + ($all * $rating)) / ($this->config['rob_s'] + $all); + + } + + /** + * Check the validity of the category of a request + * + * @access private + * @param string $category + * @return void + */ + + private function _check_category($category) + { + return $category === self::HAM or $category === self::SPAM; + } + + /** + * Learn a reference text + * + * @access public + * @param string $text + * @param const $category Either b8::SPAM or b8::HAM + * @return void + */ + + public function learn($text, $category) + { + return $this->_process_text($text, $category, self::LEARN); + } + + /** + * Unlearn a reference text + * + * @access public + * @param string $text + * @param const $category Either b8::SPAM or b8::HAM + * @return void + */ + + public function unlearn($text, $category) + { + return $this->_process_text($text, $category, self::UNLEARN); + } + + /** + * Does the actual interaction with the storage backend for learning or unlearning texts + * + * @access private + * @param string $text + * @param const $category Either b8::SPAM or b8::HAM + * @param const $action Either b8::LEARN or b8::UNLEARN + * @return void + */ + + private function _process_text($text, $category, $action) + { + + # Validate the startup + + $started_up = $this->validate(); + + if($started_up !== TRUE) + return $started_up; + + # Look if the request is okay + if($this->_check_category($category) === FALSE) + return self::TRAINER_CATEGORY_FAIL; + + # Get all tokens from $text + + $tokens = $this->_lexer->get_tokens($text); + + # Check if the lexer failed + # (if so, $tokens will be a lexer error code, if not, $tokens will be an array) + if(!is_array($tokens)) + return $tokens; + + # Pass the tokens and what to do with it to the storage backend + return $this->_database->process_text($tokens, $category, $action); + + } + +} + +?> \ No newline at end of file diff --git a/library/spam/b8/degenerator/degenerator_default.php b/library/spam/b8/degenerator/degenerator_default.php new file mode 100644 index 000000000..4ff6d882b --- /dev/null +++ b/library/spam/b8/degenerator/degenerator_default.php @@ -0,0 +1,127 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +/** + * Copyright (C) 2006-2010 Tobias Leupold + * + * @license LGPL + * @access public + * @package b8 + * @author Tobias Leupold + */ + +class b8_degenerator_default +{ + + public $degenerates = array(); + + /** + * Generates a list of "degenerated" words for a list of words. + * + * @access public + * @param array $tokens + * @return array An array containing an array of degenerated tokens for each token + */ + + public function degenerate(array $words) + { + + $degenerates = array(); + + foreach($words as $word) + $degenerates[$word] = $this->_degenerate_word($word); + + return $degenerates; + + } + + /** + * If the original word is not found in the database then + * we build "degenerated" versions of the word to lookup. + * + * @access private + * @param string $word + * @return array An array of degenerated words + */ + + protected function _degenerate_word($word) + { + + # Check for any stored words so the process doesn't have to repeat + if(isset($this->degenerates[$word]) === TRUE) + return $this->degenerates[$word]; + + $degenerate = array(); + + # Add different version of upper and lower case and ucfirst + array_push($degenerate, strtolower($word)); + array_push($degenerate, strtoupper($word)); + array_push($degenerate, ucfirst($word)); + + # Degenerate all versions + + foreach($degenerate as $alt_word) { + + # Look for stuff like !!! and ??? + + if(preg_match('/[!?]$/', $alt_word) > 0) { + + # Add versions with different !s and ?s + + if(preg_match('/[!?]{2,}$/', $alt_word) > 0) { + $tmp = preg_replace('/([!?])+$/', '$1', $alt_word); + array_push($degenerate, $tmp); + } + + $tmp = preg_replace('/([!?])+$/', '', $alt_word); + array_push($degenerate, $tmp); + + } + + # Look for ... at the end of the word + + $alt_word_int = $alt_word; + + while(preg_match('/[\.]$/', $alt_word_int) > 0) { + $alt_word_int = substr($alt_word_int, 0, strlen($alt_word_int) - 1); + array_push($degenerate, $alt_word_int); + } + + } + + # Some degenerates are the same as the original word. These don't have + # to be fetched, so we create a new array with only new tokens + + $real_degenerate = array(); + + foreach($degenerate as $deg_word) { + if($word != $deg_word) + array_push($real_degenerate, $deg_word); + } + + # Store the list of degenerates for the token + $this->degenerates[$word] = $real_degenerate; + + return $real_degenerate; + + } + +} + +?> \ No newline at end of file diff --git a/library/spam/b8/lexer/lexer_default.php b/library/spam/b8/lexer/lexer_default.php new file mode 100644 index 000000000..7b5ca22bf --- /dev/null +++ b/library/spam/b8/lexer/lexer_default.php @@ -0,0 +1,205 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +/** + * Copyright (C) 2006-2010 Tobias Leupold + * + * @license LGPL + * @access public + * @package b8 + * @author Tobias Leupold + * @author Oliver Lillie (aka buggedcom) (original PHP 5 port) + */ + +class b8_lexer_default +{ + + const LEXER_TEXT_NOT_STRING = 'LEXER_TEXT_NOT_STRING'; + const LEXER_TEXT_EMPTY = 'LEXER_TEXT_EMPTY'; + + public $config = NULL; + + # The regular expressions we use to split the text to tokens + + public $regexp = array( + 'ip' => '/([A-Za-z0-9\_\-\.]+)/', + 'raw_split' => '/[\s,\.\/"\:;\|<>\-_\[\]{}\+=\)\(\*\&\^%]+/', + 'html' => '/(<.+?>)/', + 'tagname' => '/(.+?)\s/', + 'numbers' => '/^[0-9]+$/' + ); + + /** + * Constructs the lexer. + * + * @access public + * @return void + */ + + function __construct($config) + { + $this->config = $config; + } + + /** + * Generates the tokens required for the bayesian filter. + * + * @access public + * @param string $text + * @return array Returns the list of tokens + */ + + public function get_tokens($text) + { + + # Check that we actually have a string ... + if(is_string($text) === FALSE) + return self::LEXER_TEXT_NOT_STRING; + + # ... and that it's not empty + if(empty($text) === TRUE) + return self::LEXER_TEXT_EMPTY; + + # Re-convert the text to the original characters coded in UTF-8, as + # they have been coded in html entities during the post process + $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); + + $tokens = array(); + + # Find URLs and IP addresses + + preg_match_all($this->regexp['ip'], $text, $raw_tokens); + + foreach($raw_tokens[1] as $word) { + + # Check for a dot + if(strpos($word, '.') === FALSE) + continue; + + # Check that the word is valid, min and max sizes, etc. + if($this->_is_valid($word) === FALSE) + continue; + + if(isset($tokens[$word]) === FALSE) + $tokens[$word] = 1; + else + $tokens[$word] += 1; + + # Delete the word from the text so it doesn't get re-added. + $text = str_replace($word, '', $text); + + # Also process the parts of the URLs + $url_parts = preg_split($this->regexp['raw_split'], $word); + + foreach($url_parts as $word) { + + # Again validate the part + + if($this->_is_valid($word) === FALSE) + continue; + + if(isset($tokens[$word]) === FALSE) + $tokens[$word] = 1; + else + $tokens[$word] += 1; + + } + + } + + # Split the remaining text + + $raw_tokens = preg_split($this->regexp['raw_split'], $text); + + foreach($raw_tokens as $word) { + + # Again validate the part + + if($this->_is_valid($word) === FALSE) + continue; + + if(isset($tokens[$word]) === FALSE) + $tokens[$word] = 1; + else + $tokens[$word] += 1; + + } + + # Process the HTML + + preg_match_all($this->regexp['html'], $text, $raw_tokens); + + foreach($raw_tokens[1] as $word) { + + # Again validate the part + + if($this->_is_valid($word) === FALSE) + continue; + + # If the tag has parameters, just use the tag itself + + if(strpos($word, ' ') !== FALSE) { + preg_match($this->regexp['tagname'], $word, $tmp); + $word = "{$tmp[1]}...>"; + } + + if(isset($tokens[$word]) === FALSE) + $tokens[$word] = 1; + else + $tokens[$word] += 1; + + } + + # Return a list of all found tokens + return $tokens; + + } + + /** + * Validates a token. + * + * @access private + * @param string $token The token string. + * @return boolean Returns TRUE if the token is valid, otherwise returns FALSE + */ + + private function _is_valid($token) + { + + # Validate the size of the token + + $len = strlen($token); + + if($len < $this->config['min_size'] or $len > $this->config['max_size']) + return FALSE; + + # We may want to exclude pure numbers + if($this->config['allow_numbers'] === FALSE) { + if(preg_match($this->regexp['numbers'], $token) > 0) + return FALSE; + } + + # Token is okay + return TRUE; + + } + +} + +?> \ No newline at end of file diff --git a/library/spam/b8/storage/storage_base.php b/library/spam/b8/storage/storage_base.php new file mode 100644 index 000000000..01f5a69d7 --- /dev/null +++ b/library/spam/b8/storage/storage_base.php @@ -0,0 +1,395 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +/** + * Functions used by all storage backends + * Copyright (C) 2010 Tobias Leupold + * + * @license LGPL + * @access public + * @package b8 + * @author Tobias Leupold + */ + +abstract class b8_storage_base +{ + + public $connected = FALSE; + + protected $_degenerator = NULL; + + const INTERNALS_TEXTS_HAM = 'bayes*texts.ham'; + const INTERNALS_TEXTS_SPAM = 'bayes*texts.spam'; + const INTERNALS_DBVERSION = 'bayes*dbversion'; + + const BACKEND_NOT_CONNECTED = 'BACKEND_NOT_CONNECTED'; + const DATABASE_WRONG_VERSION = 'DATABASE_WRONG_VERSION'; + const DATABASE_NOT_B8 = 'DATABASE_NOT_B8'; + + /** + * Validates the class has all it needs to work. + * + * @access protected + * @return mixed Returns TRUE if everything is okay, otherwise an error code. + */ + + protected function validate() + { + + # We set up the degenerator here, as we would have to duplicate code if it + # was done in the constructor of the respective storage backend. + $class = 'b8_degenerator_' . $this->b8_config['degenerator']; + $this->_degenerator = new $class(); + + if($this->connected !== TRUE) + return self::BACKEND_NOT_CONNECTED; + + return TRUE; + + } + + /** + * Checks if a b8 database is used and if it's version is okay + * + * @access protected + * @return mixed Returns TRUE if everything is okay, otherwise an error code. + */ + + protected function check_database() + { + + $internals = $this->get_internals(); + + if(isset($internals['dbversion'])) { + if($internals['dbversion'] == "2") { + return TRUE; + } + else { + $this->connected = FALSE; + return self::DATABASE_WRONG_VERSION; + } + } + else { + $this->connected = FALSE; + return self::DATABASE_NOT_B8; + } + + } + + /** + * Parses the "count" data of a token. + * + * @access private + * @param string $data + * @return array Returns an array of the parsed data: array(count_ham, count_spam, lastseen). + */ + + private function _parse_count($data) + { + + list($count_ham, $count_spam, $lastseen) = explode(' ', $data); + + $count_ham = (int) $count_ham; + $count_spam = (int) $count_spam; + + return array( + 'count_ham' => $count_ham, + 'count_spam' => $count_spam + ); + + } + + /** + * Get the database's internal variables. + * + * @access public + * @return array Returns an array of all internals. + */ + + public function get_internals() + { + + $internals = $this->_get_query( + array( + self::INTERNALS_TEXTS_HAM, + self::INTERNALS_TEXTS_SPAM, + self::INTERNALS_DBVERSION + ) + ); + + return array( + 'texts_ham' => (int) $internals[self::INTERNALS_TEXTS_HAM], + 'texts_spam' => (int) $internals[self::INTERNALS_TEXTS_SPAM], + 'dbversion' => (int) $internals[self::INTERNALS_DBVERSION] + ); + + } + + /** + * Get all data about a list of tags from the database. + * + * @access public + * @param array $tokens + * @return mixed Returns FALSE on failure, otherwise returns array of returned data in the format array('tokens' => array(token => count), 'degenerates' => array(token => array(degenerate => count))). + */ + + public function get($tokens) + { + + # Validate the startup + + $started_up = $this->validate(); + + if($started_up !== TRUE) + return $started_up; + + # First we see what we have in the database. + $token_data = $this->_get_query($tokens); + + # Check if we have to degenerate some tokens + + $missing_tokens = array(); + + foreach($tokens as $token) { + if(!isset($token_data[$token])) + $missing_tokens[] = $token; + } + + if(count($missing_tokens) > 0) { + + # We have to degenerate some tokens + $degenerates_list = array(); + + # Generate a list of degenerated tokens for the missing tokens ... + $degenerates = $this->_degenerator->degenerate($missing_tokens); + + # ... and look them up + + foreach($degenerates as $token => $token_degenerates) + $degenerates_list = array_merge($degenerates_list, $token_degenerates); + + $token_data = array_merge($token_data, $this->_get_query($degenerates_list)); + + } + + # Here, we have all availible data in $token_data. + + $return_data_tokens = array(); + $return_data_degenerates = array(); + + foreach($tokens as $token) { + + if(isset($token_data[$token]) === TRUE) { + + # The token was found in the database + + # Add the data ... + $return_data_tokens[$token] = $this->_parse_count($token_data[$token]); + + # ... and update it's lastseen parameter + $this->_update($token, "{$return_data_tokens[$token]['count_ham']} {$return_data_tokens[$token]['count_spam']} " . $this->b8_config['today']); + + } + + else { + + # The token was not found, so we look if we + # can return data for degenerated tokens + + # Check all degenerated forms of the token + + foreach($this->_degenerator->degenerates[$token] as $degenerate) { + + if(isset($token_data[$degenerate]) === TRUE) { + + # A degeneration of the token way found in the database + + # Add the data ... + $return_data_degenerates[$token][$degenerate] = $this->_parse_count($token_data[$degenerate]); + + # ... and update it's lastseen parameter + $this->_update($degenerate, "{$return_data_degenerates[$token][$degenerate]['count_ham']} {$return_data_degenerates[$token][$degenerate]['count_spam']} " . $this->b8_config['today']); + + } + + } + + } + + } + + # Now, all token data directly found in the database is in $return_data_tokens + # and all data for degenerated versions is in $return_data_degenerates + + # First, we commit the changes to the lastseen parameters + $this->_commit(); + + # Then, we return what we have + return array( + 'tokens' => $return_data_tokens, + 'degenerates' => $return_data_degenerates + ); + + } + + /** + * Stores or deletes a list of tokens from the given category. + * + * @access public + * @param array $tokens + * @param const $category Either b8::HAM or b8::SPAM + * @param const $action Either b8::LEARN or b8::UNLEARN + * @return void + */ + + public function process_text($tokens, $category, $action) + { + + # Validate the startup + + $started_up = $this->validate(); + + if($started_up !== TRUE) + return $started_up; + + # No matter what we do, we first have to check what data we have. + + # First get the internals, including the ham texts and spam texts counter + $internals = $this->get_internals(); + + # Then, fetch all data for all tokens we have (and update their lastseen parameters) + $token_data = $this->_get_query(array_keys($tokens)); + + # Process all tokens to learn/unlearn + + foreach($tokens as $token => $count) { + + if(isset($token_data[$token])) { + + # We already have this token, so update it's data + + # Get the existing data + list($count_ham, $count_spam, $lastseen) = explode(' ', $token_data[$token]); + $count_ham = (int) $count_ham; + $count_spam = (int) $count_spam; + + # Increase or decrease the right counter + + if($action === b8::LEARN) { + if($category === b8::HAM) + $count_ham += $count; + elseif($category === b8::SPAM) + $count_spam += $count; + } + + elseif($action == b8::UNLEARN) { + if($category === b8::HAM) + $count_ham -= $count; + elseif($category === b8::SPAM) + $count_spam -= $count; + } + + # We don't want to have negative values + + if($count_ham < 0) + $count_ham = 0; + + if($count_spam < 0) + $count_spam = 0; + + # Now let's see if we have to update or delete the token + if($count_ham !== 0 or $count_spam !== 0) + $this->_update($token, "$count_ham $count_spam " . $this->b8_config['today']); + else + $this->_del($token); + + } + + else { + + # We don't have the token. If we unlearn a text, we can't delete it + # as we don't have it anyway, so just do something if we learn a text + + if($action === b8::LEARN) { + + if($category === b8::HAM) + $data = '1 0 '; + elseif($category === b8::SPAM) + $data = '0 1 '; + + $data .= $this->b8_config['today']; + + $this->_put($token, $data); + + } + + } + + } + + # Now, all token have been processed, so let's update the right text + + if($action === b8::LEARN) { + + if($category === b8::HAM) { + $internals['texts_ham']++; + $this->_update(self::INTERNALS_TEXTS_HAM, $internals['texts_ham']); + } + + elseif($category === b8::SPAM) { + $internals['texts_spam']++; + $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam']); + } + + } + + elseif($action == b8::UNLEARN) { + + if($category === b8::HAM) { + + $internals['texts_ham']--; + + if($internals['texts_ham'] < 0) + $internals['texts_ham'] = 0; + + $this->_update(self::INTERNALS_TEXTS_HAM, $internals['texts_ham']); + + } + + elseif($category === b8::SPAM) { + + $internals['texts_spam']--; + + if($internals['texts_spam'] < 0) + $internals['texts_spam'] = 0; + + $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam']); + + } + + } + + # We're done and can commit all changes to the database now + $this->_commit(); + + } + +} + +?> \ No newline at end of file diff --git a/library/spam/b8/storage/storage_dba.php b/library/spam/b8/storage/storage_dba.php new file mode 100644 index 000000000..04618b23e --- /dev/null +++ b/library/spam/b8/storage/storage_dba.php @@ -0,0 +1,198 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +/** + * The DBA (Berkeley DB) abstraction layer for communicating with the database. + * Copyright (C) 2006-2010 Tobias Leupold + * + * @license LGPL + * @access public + * @package b8 + * @author Tobias Leupold + */ + +class b8_storage_dba extends b8_storage_base +{ + + public $config = array( + 'database' => 'wordlist.db', + 'handler' => 'db4', + ); + + public $b8_config = array( + 'degenerator' => NULL, + 'today' => NULL + ); + + private $_db = NULL; + + const DATABASE_CONNECTION_FAIL = 'DATABASE_CONNECTION_FAIL'; + + /** + * Constructs the database layer. + * + * @access public + * @param string $config + */ + + function __construct($config, $degenerator, $today) + { + + # Pass some variables of the main b8 config to this class + $this->b8_config['degenerator'] = $degenerator; + $this->b8_config['today'] = $today; + + # Validate the config items + if(count($config) > 0) { + foreach ($config as $name => $value) { + $this->config[$name] = (string) $value; + } + } + + } + + /** + * Closes the database connection. + * + * @access public + * @return void + */ + + function __destruct() + { + if($this->_db !== NULL) { + dba_close($this->_db); + $this->connected = FALSE; + } + } + + /** + * Connect to the database and do some checks. + * + * @access public + * @return mixed Returns TRUE on a successful database connection, otherwise returns a constant from b8. + */ + + public function connect() + { + + # Have we already connected? + if($this->_db !== NULL) + return TRUE; + + # Open the database connection + $this->_db = dba_open(dirname(__FILE__) . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . $this->config['database'], "w", $this->config['handler']); + + if($this->_db === FALSE) { + $this->connected = FALSE; + $this->_db = NULL; + return self::DATABASE_CONNECTION_FAIL; + } + + # Everything is okay and connected + + $this->connected = TRUE; + + # Let's see if this is a b8 database and the version is okay + return $this->check_database(); + + } + + /** + * Does the actual interaction with the database when fetching data. + * + * @access protected + * @param array $tokens + * @return mixed Returns an array of the returned data in the format array(token => data) or an empty array if there was no data. + */ + + protected function _get_query($tokens) + { + + $data = array(); + + foreach ($tokens as $token) { + + $count = dba_fetch($token, $this->_db); + + if($count !== FALSE) + $data[$token] = $count; + + } + + return $data; + + } + + /** + * Store a token to the database. + * + * @access protected + * @param string $token + * @param string $count + * @return bool TRUE on success or FALSE on failure + */ + + protected function _put($token, $count) { + return dba_insert($token, $count, $this->_db); + } + + /** + * Update an existing token. + * + * @access protected + * @param string $token + * @param string $count + * @return bool TRUE on success or FALSE on failure + */ + + protected function _update($token, $count) + { + return dba_replace($token, $count, $this->_db); + } + + /** + * Remove a token from the database. + * + * @access protected + * @param string $token + * @return bool TRUE on success or FALSE on failure + */ + + protected function _del($token) + { + return dba_delete($token, $this->_db); + } + + /** + * Does nothing :-D + * + * @access protected + * @return void + */ + + protected function _commit() + { + # We just need this function because the (My)SQL backend(s) need it. + return; + } + +} + +?> \ No newline at end of file diff --git a/library/spam/b8/storage/storage_mysql.php b/library/spam/b8/storage/storage_mysql.php new file mode 100644 index 000000000..022536350 --- /dev/null +++ b/library/spam/b8/storage/storage_mysql.php @@ -0,0 +1,351 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +/** + * The MySQL abstraction layer for communicating with the database. + * Copyright (C) 2009 Oliver Lillie (aka buggedcom) + * Copyright (C) 2010-2011 Tobias Leupold + * + * @license LGPL + * @access public + * @package b8 + * @author Oliver Lillie (aka buggedcom) (original PHP 5 port and optimizations) + * @author Tobias Leupold + */ + +class b8_storage_mysql extends b8_storage_base +{ + + public $config = array( + 'database' => 'b8_wordlist', + 'table_name' => 'b8_wordlist', + 'host' => 'localhost', + 'user' => FALSE, + 'pass' => FALSE, + 'connection' => NULL + ); + + public $b8_config = array( + 'degenerator' => NULL, + 'today' => NULL + ); + + private $_connection = NULL; + private $_deletes = array(); + private $_puts = array(); + private $_updates = array(); + + const DATABASE_CONNECTION_FAIL = 'DATABASE_CONNECTION_FAIL'; + const DATABASE_CONNECTION_ERROR = 'DATABASE_CONNECTION_ERROR'; + const DATABASE_CONNECTION_BAD_RESOURCE = 'DATABASE_CONNECTION_BAD_RESOURCE'; + const DATABASE_SELECT_ERROR = 'DATABASE_SELECT_ERROR'; + const DATABASE_TABLE_ACCESS_FAIL = 'DATABASE_TABLE_ACCESS_FAIL'; + const DATABASE_WRONG_VERSION = 'DATABASE_WRONG_VERSION'; + + /** + * Constructs the database layer. + * + * @access public + * @param string $config + */ + + function __construct($config, $degenerator, $today) + { + + # Pass some variables of the main b8 config to this class + $this->b8_config['degenerator'] = $degenerator; + $this->b8_config['today'] = $today; + + # Validate the config items + + if(count($config) > 0) { + + foreach ($config as $name => $value) { + + switch($name) { + + case 'table_name': + case 'host': + case 'user': + case 'pass': + case 'database': + $this->config[$name] = (string) $value; + break; + + case 'connection': + + if($value !== NULL) { + + if(is_resource($value) === TRUE) { + $resource_type = get_resource_type($value); + $this->config['connection'] = $resource_type !== 'mysql link' && $resource_type !== 'mysql link persistent' ? FALSE : $value; + } + + else + $this->config['connection'] = FALSE; + + } + + break; + + } + + } + + } + + } + + /** + * Closes the database connection. + * + * @access public + * @return void + */ + + function __destruct() + { + + if($this->_connection === NULL) + return; + + # Commit any changes before closing + $this->_commit(); + + # Just close the connection if no link-resource was passed and b8 created it's own connection + if($this->config['connection'] === NULL) + mysql_close($this->_connection); + + $this->connected = FALSE; + + } + + /** + * Connect to the database and do some checks. + * + * @access public + * @return mixed Returns TRUE on a successful database connection, otherwise returns a constant from b8. + */ + + public function connect() + { + + # Are we already connected? + if($this->connected === TRUE) + return TRUE; + + # Are we using an existing passed resource? + if($this->config['connection'] === FALSE) { + # ... yes we are, but the connection is not a resource, so return an error + $this->connected = FALSE; + return self::DATABASE_CONNECTION_BAD_RESOURCE; + } + + elseif($this->config['connection'] === NULL) { + + # ... no we aren't so we have to connect. + + if($this->_connection = mysql_connect($this->config['host'], $this->config['user'], $this->config['pass'])) { + if(mysql_select_db($this->config['database'], $this->_connection) === FALSE) { + $this->connected = FALSE; + return self::DATABASE_SELECT_ERROR . ": " . mysql_error(); + } + } + else { + $this->connected = FALSE; + return self::DATABASE_CONNECTION_ERROR; + } + + } + + else { + # ... yes we are + $this->_connection = $this->config['connection']; + } + + # Just in case ... + if($this->_connection === NULL) { + $this->connected = FALSE; + return self::DATABASE_CONNECTION_FAIL; + } + + # Check to see if the wordlist table exists + if(mysql_query('DESCRIBE ' . $this->config['table_name'], $this->_connection) === FALSE) { + $this->connected = FALSE; + return self::DATABASE_TABLE_ACCESS_FAIL . ": " . mysql_error(); + } + + # Everything is okay and connected + $this->connected = TRUE; + + # Let's see if this is a b8 database and the version is okay + return $this->check_database(); + + } + + /** + * Does the actual interaction with the database when fetching data. + * + * @access protected + * @param array $tokens + * @return mixed Returns an array of the returned data in the format array(token => data) or an empty array if there was no data. + */ + + protected function _get_query($tokens) + { + + # Construct the query ... + + if(count($tokens) > 0) { + + $where = array(); + + foreach ($tokens as $token) { + $token = mysql_real_escape_string($token, $this->_connection); + array_push($where, $token); + } + + $where = 'token IN ("' . implode('", "', $where) . '")'; + } + + else { + $token = mysql_real_escape_string($token, $this->_connection); + $where = 'token = "' . $token . '"'; + } + + # ... and fetch the data + + $result = mysql_query(' + SELECT token, count + FROM ' . $this->config['table_name'] . ' + WHERE ' . $where . '; + ', $this->_connection); + + $data = array(); + + while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) + $data[$row['token']] = $row['count']; + + mysql_free_result($result); + + return $data; + + } + + /** + * Store a token to the database. + * + * @access protected + * @param string $token + * @param string $count + * @return void + */ + + protected function _put($token, $count) { + $token = mysql_real_escape_string($token, $this->_connection); + $count = mysql_real_escape_string($count, $this->_connection);; + array_push($this->_puts, '("' . $token . '", "' . $count . '")'); + } + + /** + * Update an existing token. + * + * @access protected + * @param string $token + * @param string $count + * @return void + */ + + protected function _update($token, $count) + { + $token = mysql_real_escape_string($token, $this->_connection); + $count = mysql_real_escape_string($count, $this->_connection); + array_push($this->_updates, '("' . $token . '", "' . $count . '")'); + } + + /** + * Remove a token from the database. + * + * @access protected + * @param string $token + * @return void + */ + + protected function _del($token) + { + $token = mysql_real_escape_string($token, $this->_connection); + array_push($this->_deletes, $token); + } + + /** + * Commits any modification queries. + * + * @access protected + * @return void + */ + + protected function _commit() + { + + if(count($this->_deletes) > 0) { + + $result = mysql_query(' + DELETE FROM ' . $this->config['table_name'] . ' + WHERE token IN ("' . implode('", "', $this->_deletes) . '"); + ', $this->_connection); + + if(is_resource($result) === TRUE) + mysql_free_result($result); + + $this->_deletes = array(); + + } + + if(count($this->_puts) > 0) { + + $result = mysql_query(' + INSERT INTO ' . $this->config['table_name'] . '(token, count) + VALUES ' . implode(', ', $this->_puts) . ';', $this->_connection); + + if(is_resource($result) === TRUE) + mysql_free_result($result); + + $this->_puts = array(); + + } + + if(count($this->_updates) > 0) { + + $result = mysql_query(' + INSERT INTO ' . $this->config['table_name'] . '(token, count) + VALUES ' . implode(', ', $this->_updates) . ' + ON DUPLICATE KEY UPDATE ' . $this->config['table_name'] . '.count = VALUES(count);', $this->_connection); + + if(is_resource($result) === TRUE) + mysql_free_result($result); + + $this->_updates = array(); + + } + + } + +} + +?> \ No newline at end of file diff --git a/library/spam/doc/COPYING b/library/spam/doc/COPYING new file mode 100644 index 000000000..8add30ad5 --- /dev/null +++ b/library/spam/doc/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/library/spam/doc/ChangeLog b/library/spam/doc/ChangeLog new file mode 100644 index 000000000..78a4fc77f --- /dev/null +++ b/library/spam/doc/ChangeLog @@ -0,0 +1,179 @@ +2010-12-30 Tobias Leupold + + * Release: Version 0.5.1 + + * Bigger changes: + - Fixed some issues with the scope of variables leading to problems when multiple instances of b8 are created. Thanks to Mike Creuzer for the bug report :-) + - Centralized the loading of class definition files in the b8 constructor and created a function to handle the inclusion. + + * b8.php: Return a lexer error code instead of a rating if the lexer failed. The lexer never returned FALSE but b8 checked only for this value to validate the lexer didn't fail. Thanks to Matt Friedman for the bug report :-) + + * lexer/lexer_default.php: A bit of code cleanup: less useless nesting. + + * doc/readme.*: Updated the documentation, added a FAQ. + +2010-06-27 Tobias Leupold + + * Release: Version 0.5-r1 + + * doc/readme.*: Updated the documentation; forgot the newly introduced b8::HAM and b8::SPAM variables. Added some additional information about the storage model. + +2010-06-02 Tobias Leupold + + * Release: Version 0.5 + + * 100.000 Changes (new major release!), at a glance: + - No PHP 4 compatibility anymore. Much cleaner code base with less hacks. + - Completely reworked storage model. The SQL performance increased dramatically, the Berkeley DB performance remains as fast as it always has been. + - Better lexer which can also handle non-latin1 texts in a nice way, so that e. g. Cyrillic or Chinese texts can be classified more performant. + - No config files anymore, multiple instances of b8 can be now created in the same script with different configuration, databases and no problems. + - No spooky administration interface anymore that needs an SQL database, even if Berkeley DB is used (anybody who actually used this?! I never did ;-). + - No "install" scripts and routines and a less end-user compatible documentation. Anybody integrating b8 in his homepage won't be an end-user, will he? + +2009-02-03 Oliver Lillie (aka buggedcom) + + * Revision: 221 (the original PHP 5 port) + + * Rewrote Tobias' original class for optimisation and PHP 5 functionality. + + * Improved database mysql query useage by over ~820% + + * Class is faster, ~20%. + + * Slight increase in memory usage, but it's small and given the advantages of the speed increase and query reduction it's worth it. + + * Removed install code from mysql class and added a sql file. Anyone who wants to use this is generally going to be more advanced anyway and see the sql to install. + +2009-02-03 Tobias Leupold + + * Release: Version 0.4.4 -- changed the license type from GPL to LGPL + +2008-06-27 Tobias Leupold + + * Release: Version 0.4.3 -- no bugs found ... so let's make a release with only small changes ;-) + + * b8.php: Removed debugging messages that were commented out anyway + + * storage/storage_mysql.php: Made it possible to pass both a MySQL-link resource and a table name to b8. This makes b8 useable in the Redaxo CMS (and probably others) + + * doc/readme.htm: Updated documentation accordingly + +2008-02-17 Tobias Leupold + + * Release: Version 0.4.2 + + * interface/backup.php: the bayes*dbversion tag is now written to a database emptied by drop(), so that it will be useable without an error message even if no backup is recovered afterwards. + + * doc/readme.htm: added a security note to the configuration section (htaccess should be used to avoid everybody to be able to see the configuration) + +2007-09-17 Tobias Leupold + + * Release: Version 0.4.1 + + * storage/storage_mysql.php: fixed b8 crashing when getting passed a persistent MySQL resource link. Thanks to Paul Chapman for the bug report :-) + +2007-06-08 Tobias Leupold + + * Release: Version 0.4 + + * Let's go the whole hog. b8's class is now "b8" and no more "bayes", and all internal variables have now according names. + + * Reworked the whole (surprisingly crappy) implementation of b8. No more global() calls, everything happens inside the classes now. Made that whole stuff really object oriented (as good as possible with PHP's poor OOP model ;-). + + * No more PHP code in the configuration files. + + * Created an extra lexer class. This is now also configurable. + + * Storage classes now can create their own databases when this is requested by the configuration. + + * MySQL calls are no random shots anymore: either, a MySQL-link resource is passed to b8 on startup which will be used for the queries, or the class sets up it's own link. Same for SQLite. + + * The interface now uses a separate storage backend capable of SQL. In this way, we _really_ can query the database for e. g. an ordered list of tokens. After doing what we wanted with this work database, the b8 database can be synced with it. + + * Added a lot of verbose error handling. + + * Fixed a dumb error: all tokens from a text were used for the spamminess calculation, because two for() loops both used $i as their counter. D'oh!!! Now, the filter's performance is way better. + + * Catched on the way how that whole math stuff works a little more ;-) Now, the calculation of the single probabilities proposed by Mr. Robinson does a little more the stuff it was intended to do, because ... + + * Made some calculation constants parameters: the number of tokens to use, the default rating for unknown tokens and Gary Robinson's s constant. + + * Introduced an optional minimum deviation that a token's rating must have to be considered in the spamminess calculation. + + * The default extreme ratings for tokens only in ham or spam are now optional. One can also choose to calculate all ratings by Mr. Robinson's method. + + * Noticed that text primary keys are not case sensitive by default in MySQL, which has a noticeable impact on the filter's performance. Informed the MySQL users about that. + + * The whole code sucks much less ;-) b8 should be way more user friendly now. + + * Re-wrote the whole documentation. + + * Fixed the ChangeLog :-) + +2007-02-08 Tobias Leupold + + * Release: Version 0.3.3 again ;-) + + * bayes-php is now b8. See http://www.nasauber.de/blog/text.php?text=58 for details :-) Thanks to Tobias Lang (http://langt.net/) for this cool new name! + +2007-01-05 Tobias Leupold + + * Release: Version 0.3.3 + + * Renamed the internal BerkeleyDB handle from "$db" to the less general name "$bayes_php_db" due to an collision with phpwcms's (http://www.phpwcms.de/) global $db variable and potentially other php programs. + + * Commented out Laurent Goussard's SQLite storage class by default, as it's try { } catch { } calls break PHP 4 + +2006-09-03 Tobias Leupold + + * Release: Version 0.3.2 + + * Laurent Goussard (loranger@free.fr) contributed an SQLite storage class(which needs PHP 5). + + * I finally added my eMail address to the sources ;-) + +2006-07-24 Tobias Leupold + + * Release: Version 0.3.1 + + * Fixed a problem in the unlearn() function: If a text was unlearned that wasn't learned before (accidentaly), it could happen that the count parameter for this text was smaller than 0, breaking the spamminess calulation + +2006-07-02 Tobias Leupold + + * Release: Version 0.3 + + * Improved the get_tokens() function; the filter should now be a lot more performant, especially with short texts + + * Added the "lastseen" parameter for each token to make the database maintainable (outdated tokens can be deleted) + + * Added a real database maintainance interface + +2006-06-12 Tobias Leupold + + * Release: Version 0.2.1 + + * Fixed a problem in get_tokens() (if it was called more than once, tokens were counted more often than they appeared in the text) + + * Slightly enhanced the default index.php interface: after learning a text as Ham or Spam, the rating before and after it is displayed to inform the user about it + +2006-05-21 Tobias Leupold + + * Release: Version 0.2 + + * Comments now in English (to pretend international success of bayes-php ;-) + + * Recommendations of Paul Graham's article "Better Bayesian Filtering" ( http://www.paulgraham.com/better.html ) are now considered: Tokens that only appear in Ham or Spam and not in the other category are rated with 0.9998 or 0.0002 if they were less than 10 times in Ham or Spam and with 0.9999 or 0.0001 if they appeared more that 10 times. This should allow the filter to differentiate spam texts more sharp from ham texts. Also, token "degeneration" as described in the article is performed for unknown tokens to estimate their spamminess. + + * The database connect is now swapped in a separate configuration file, so only this file has to be preserved if bayes-php is updated and only this file has to be changed to configure the script. + +2006-03-29 Tobias Leupold + + * Release: Version 0.1.1 + + * get_tokens() beachtet jetzt auch HTML-Tags und Wörter mit Akzenten und Apostrophen + + * Verschiedene Kleinigkeiten "sauber" gemacht :-) + +2006-03-05 Tobias Leupold + + * Added 2007-06-08: Initial release (Version 0.1) diff --git a/library/spam/doc/readme.htm b/library/spam/doc/readme.htm new file mode 100644 index 000000000..727d5ae5f --- /dev/null +++ b/library/spam/doc/readme.htm @@ -0,0 +1,707 @@ + + + + + + +b8: readme + + + + + +
+

b8: readme

+ +++ + + + + + + + + + +
Author:Tobias Leupold
Homepage:http://nasauber.de/
Contact:tobias.leupold@web.de
Date:2010-12-23
+ +
+

1   Description of b8

+
+

1.1   What is b8?

+

b8 is a spam filter implemented in PHP. It is intended to keep your weblog or guestbook spam-free. The filter can be used anywhere in your PHP code and tells you whether a text is spam or not, using statistical text analysis. See How does it work? for details about this. To be able to do this, b8 first has to learn some spam and some ham example texts to decide what's good and what's not. If it makes mistakes classifying unknown texts, they can be corrected and b8 learns from the corrections, getting better with each learned text.

+

At the moment of this writing, b8 has classified 14411 guestbook entries and weblog comments on my homepage since december 2006. 131 were ham. 39 spam texts (0.27 %) have been rated as ham (false negatives), with not even one false positive (ham message classified as spam). This results in a sensitivity of 99.73 % (the probability that a spam text will actually be rated as spam) and a specifity of 100 % (the probability that a ham text will actually be rated as ham) for me. I hope, you'll get the same good results :-)

+

Basically, b8 is a statistical ("Bayesian"[1]) spam filter like Bogofilter or SpamBayes, but it is not intended to classify e-mails. When I started to write b8, I didn't find a good PHP spam filter (or any spam filter that wasn't just some example code how one could implement a Bayesian spam filter in PHP) that was intended to filter weblog or guestbook entries. That's why I had to write my own ;-)
+Caused by it's purpose, the way b8 works is slightly different from most of the Bayesian email spam filters out there. See What's different? if you're interested in the details.

+ + + + + +
[1]A mathematician told me that the math in b8 actually does not use Bayes' theorem but some derived algorithms that are just related to it. So … let's simply believe that and stop claiming b8 was a Bayesian spam filter ;-)
+
+
+

1.2   How does it work?

+

b8 basically uses the math and technique described in Paul Graham's article "A Plan For Spam" [2] to distinguish ham and spam. The improvements proposed in Graham's article "Better Bayesian Filtering" [3] and Gary Robinson's article "Spam Detection" [4] have also been considered. See also the article "A Statistical Approach to the Spam Problem" [5].

+

b8 cuts the text to classify to pieces, extracting stuff like e-mail addresses, links and HTML tags. For each such token, it calculates a single probability for a text containing it being spam, based on what the filter has learned so far. When the token was not seen before, b8 tries to find similar ones using the "degeneration" described in [3] and uses the most relevant value found. If really nothing is found, b8 assumes a default rating for this token for the further calculations.
+Then, b8 takes the most relevant values (which have a rating far from 0.5, which would mean we don't know what it is) and calculates the probability that the whole text is spam by the inverse chi-square function described in [4]. +There are some parameters that can be set which influence the filter's behaviour (see below).

+

In short words: you give b8 a text and it returns a value between 0 and 1, saying it's ham when it's near 0 and saying it's spam when it's near 1.

+
+
+

1.3   What do I need for it?

+

Not much! You just need PHP 5 on the server where b8 will be used (b8 version 0.5 finally dropped PHP 4 compatibility – thankfully ;-) and a proper storage possibility for the wordlists. I strongly recommend using Berkeley DB. See below how you can check if you can use it and why you should use it. If the server's PHP wasn't compiled with Berkeley DB support, a MySQL table can be used alternatively.

+
+
+

1.4   What's different?

+

b8 is designed to classify weblog or guestbook entries, not e-mails. For this reason, it uses a slightly different technique than most of the other statistical spam filters out there use.

+

My experience was that spam entries on my weblog or guestbook were often quite short, sometimes just something like "123abc" as text and a link to a suspect homepage. Some spam bots don't even made a difference between e. g. the "name" and "text" fields and posted their text as email address, for example. Considering this, b8 just takes one string to classify, making no difference between "headers" and "text".
+The other thing is that most statistical spam filters count one token one time, no matter how often it appears in the text (as Graham describes it in [2]). b8 does count how often a token was seen and learns or considers this. Additionally, the number of learned ham and spam texts are saved and used as the calculation base for the single probabilities. Why this? Because a text containing one link (no matter where it points to, just indicated by a "http://" or a "www.") might not be spam, but a text containing 20 links might be.

+

This means that b8 might be good for classifying weblog or guestbook entries (I really think it is ;-) – but very likely, it will work quite poor when being used for something else (like classifying e-mails). But as said above, for this task, there are a lot of very good filters out there to choose from.

+
+
+
+

2   Update from prior versions

+

If this is a new b8 installation, read on at the Installation section!

+
+

2.1   Update from bayes-php version 0.2.1 or earlier

+

Please first follow the database update instructions of the bayes-php-0.3 release if you update from a version prior to bayes-php-0.3 and then read the following paragraph about updating from a version <0.3.3.

+
+
+

2.2   Update from bayes-php version 0.3 or later

+
+
You use Berkeley DB?
+
Everything's fine, you can simply continue using your database.
+
You use MySQL?
+
The CREATE statement of b8's wordlist has changed. The best is probably to create a dump via your favorite administration tool or script, create the new table and re-insert all data. The layout is still the same: there's one "token" column and one "data" column. Having done that, you can keep using your data.
+
You use SQLite?
+
Sorry, at the moment, there's no SQLite backend for b8. But we're working on it :-)
+
+

The configuration model of b8 has changed. Please read through the Configuration section and update your configuration accordingly.

+

b8's lexer has been partially re-written. It should now be able to handle all kind of non-latin-1 input, like cyrillic, chinese or japanese texts. Caused by this fact, much more tokens will be recognized when classifying such texts. Therefore, you could get different results in b8's ratings, even if the same database is used and although the math is still the same.

+

b8 0.5 introduced two constants that can be used in the learn() and unlearn() functions: b8::HAM and b8::SPAM. The literal values "ham" and "spam" can still be used anyway.

+
+
+
+

3   Installation

+

Installing b8 on your server is quite easy. You just have to provide the needed files. To do this, you could just upload the whole b8 subdirectory to the base directory of your homepage. It contains the filter itself and all needed backend classes. The other directories (doc, example and install) are not used by b8.

+

That's it ;-)

+
+
+

4   Configuration

+

The configuration is passed as arrays when instantiating a new b8 object. Two arrays can be passed to b8, one containing b8's base configuration and some settings for the lexer (which should be common for all lexer classes, in case some other lexer than the default one will be written one day) and one for the storage backend.
+You can have a look at example/index.php to see how this can be done. Using b8 in your scripts also shows example code showing how b8 can be included in a PHP script.

+

Not all values have to be set. When some values are missing, the default ones will be used. If you do use the default settings, you don't have to pass them to b8.

+
+

4.1   b8's base configuration

+

All these values can be set in the "config_b8" array (the first parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the first argument.

+

These are some basic settings telling b8 which backend classes to use:

+
+
+
storage
+

This defines which storage backend will be used to save b8's wordlist. Currently, two backends are available: Berkeley DB (dba) and MySQL (mysql). At the moment, b8 does not support SQLite (as the previous version did), but it will be (hopefully) re-added in one of the next releases. The default is dba (string).

+
+
Berkeley DB
+
This is the preferred storage backend. It was the original backend for the filter and remains the most performant. b8's storage model is optimized for this database, as it is really fast and fits perfectly to what the filter needs to do the job. All content is saved in a single file, you don't need special user rights or a database server.
+If you don't know whether your server's PHP can use a Berkeley DB, simply run the script install/setup_berkeleydb.php. If it shows a Berkeley DB handler, please use this backend.
+
MySQL
+
As some webspace hosters don't allow using a Berkeley DB (but please be sure to check if you can use it!), but most do provide a MySQL server, using a MySQL table for the wordlist is provided as an alternative storage method. As said above, b8 was always intended to use a Berkeley DB. It doesn't use or need SQL to query the database. So, very likely, this will work less performant, produce a lot of unnecessary overhead and waste computing power. But it will do fine anyway!
+
+

See Configuration of the storage backend for the settings of the chosen backend.

+
+
degenerator
+
The degenerator class to be used. See How does it work? and [3] if you're interested in what "degeneration" is. Defaults to default (string). At the moment, only one degenerator exists, so you probably don't want to change this unless you have written your own degenerator.
+
lexer
+

The lexer class to be used. Defaults to default (string). At the moment, only one lexer exists, so you probably don't want to change this unless you have written your own lexer.

+

The behaviour of the lexer can be additionally configured with the following variables:

+
+
+
min_size
+
The minimal length for a token to be considered when calculating the rating of a text. Defaults to 3 (integer).
+
max_size
+
The maximal length for a token to be considered when calculating the rating of a text. Defaults to 30 (integer).
+
allow_numbers
+
Should pure numbers also be considered? Defaults to FALSE (boolean).
+
+
+
+
+
+

The following settings influence the mathematical internals of b8. If you want to experiment, feel free to play around with them; but be warned: wrong settings of these values will result in poor performance or could even "short-circuit" the filter.
+Leave these values as they are unless you know what you are doing!

+

The "Statistical discussion about b8" [6] shows why the default values are the default ones.

+
+
+
use_relevant
+
This tells b8 how many tokens should be used when calculating the spamminess of a text. The default setting is 15 (integer). This seems to be a quite reasonable value. When using to many tokens, the filter will fail on texts filled with useless stuff or with passages from a newspaper, etc. not being very spammish.
+The tokens counted multiple times (see above) are added in addition to this value. They don't replace other ratings.
+
min_dev
+
This defines a minimum deviation from 0.5 that a token's rating must have to be considered when calculating the spamminess. Tokens with a rating closer to 0.5 than this value will simply be skipped.
+If you don't want to use this feature, set this to 0. Defaults to 0.2 (float). Read [6] before increasing this.
+
rob_x
+
This is Gary Robinson's x constant (cf. [4]). A completely unknown token will be rated with the value of rob_x. The default 0.5 (float) seems to be quite reasonable, as we can't say if a token that also can't be rated by degeneration is good or bad.
+If you receive much more spam than ham or vice versa, you could change this setting accordingly.
+
rob_s
+
This is Gary Robinson's s constant. This is essentially the probability that the rob_x value is correct for a completely unknown token. It will also shift the probability of rarely seen tokens towards this value. The default is 0.3 (float)
+See [4] for a closer description of the s constant and read [6] for specific information about this constant in b8's algorithms.
+
+
+
+
+

4.2   Configuration of the storage backend

+

All the following values can be set in the "config_database" array (the second parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the second argument.

+
+

4.2.1   Settings for the Berkeley DB (DBA) backend

+
+
database
+
The filename of the database file, relative to the location of b8.php. Defaults to wordlist.db (string).
+
handler
+
The DBA handler to use (cf. the PHP documentation and Setting up a new Berkeley DB). Defaults to db4 (string).
+
+
+
+

4.2.2   Settings for the MySQL backend

+
+
database
+
The database containing b8's wordlist table. Defaults to b8_wordlist (string).
+
table_name
+
The table containing b8's wordlist. Defaults to b8_wordlist (string).
+
host
+
The host of the MySQL server. Defaults to localhost (string).
+
user
+
The user name used to open the database connection. Defaults to FALSE (boolean).
+
pass
+
The password required to open the database connection. Defaults to FALSE (boolean).
+
connection
+
An existing MySQL link-resource that can be used by b8. Defaults to NULL (NULL).
+
+
+
+
+
+

5   Using b8

+

Now, that everything is configured, you can start to use b8. A sample script that shows what can be done with the filter exists in example/index.php. The best thing for testing how all this works is to use this script before using b8 in your own scripts.

+

Before you can start, you have to setup a database so that b8 can store a wordlist.

+
+

5.1   Setting up a new database

+
+

5.1.1   Setting up a new Berkeley DB

+

I wrote a script to setup a new Berkeley DB for b8. It is located in install/setup_berkeleydb.php. Just run this script on your server and be sure that the directory containing it has the proper access rights set so that the server's HTTP server user or PHP user can create a new file in it (probably 0777). The script is quite self-explaining, just run it.

+

Of course, you can also create a Berkeley DB by hand. In this case, you just have to insert three keys:

+
+bayes*dbversion  => 2
+bayes*texts.ham  => 0
+bayes*texts.spam => 0
+
+

Be sure to set the right DBA handler in the storage backend configuration if it's not db4.

+
+
+

5.1.2   Setting up a new MySQL table

+

The SQL file install/setup_mysql.sql contains both the create statement for the wordlist table of b8 and the INSERT statements for adding the necessary internal variables.

+

Simply change the table name according to your needs (or leave it as it is ;-) and run the SQL to setup a b8 wordlist MySQL table.

+
+
+
+

5.2   Using b8 in your scripts

+

Just have a look at the example script located in example/index.php to see how you can include b8 in your scripts. Essentially, this strips down to:

+
+# Include the b8 code
+require "{$_SERVER['DOCUMENT_ROOT']}/b8/b8.php";
+
+# Do some configuration
+
+$config_b8 = array(
+        'some_key' => 'some_value',
+        'foo' => 'bar'
+);
+
+$config_database = array(
+        'some_key' => 'some_value',
+        'foo' => 'bar'
+);
+
+# Create a new b8 instance
+$b8 = new b8($config_b8, $config_database);
+
+

b8 provides three functions in an object oriented way (called e. g. via $b8->classify($text)):

+
+
learn($text, $category)
+
This saves the reference text $text (string) in the category $category (b8 constant).
+b8 0.5 introduced two constants that can be used as $category: b8::HAM and b8::SPAM. To be downward compatible with older versions of b8, the literal values "ham" and "spam" (case-sensitive strings) can still be used here.
+
unlearn($text, $category)
+
This function just exists to delete a text from a category in which is has been stored accidentally before. It deletes the reference text $text (string) from the category $category (either the constants b8::HAM or b8::SPAM or the literal case-sensitive strings "ham" or "spam" – cf. above).
+Don't delete a spam text from ham after saving it in spam or vice versa, as long you don't have stored it accidentally in the wrong category before! This will not improve performance, quite the opposite: it will actually break the filter after a time, as the counter for saved ham or spam texts will reach 0, although you have ham or spam tokens stored: the filter will try to remove texts from the ham or spam data which have never been stored there, decrease the counter for tokens which are found just skip the non-existing words.
+
classify($text)
+
This function takes the text $text (string), calculates it's probability for being spam it and returns a value between 0 and 1 (float).
+A value close to 0 says the text is more likely ham and a value close to 1 says the text is more likely spam. What to do with this value is your business ;-) See also Tips on operation below.
+
+
+
+
+

6   Tips on operation

+

Before b8 can decide whether a text is spam or ham, you have to tell it what you consider as spam or ham. At least one learned spam or one learned ham text is needed to calculate anything. To get good ratings, you need both learned ham and learned spam texts, the more the better.
+What's considered as "ham" or "spam" can be very different, depending on the operation site. On my homepage, practically each and every text posted in English or using cyrillic letters is spam. On an English or Russian homepage, this will be not the case. So I think it's not really meaningful to provide some "spam data" to start. Just train b8 with "your" spam and ham.

+

For the practical use, I advise to give the filter all data availible. E. g. name, email address, homepage, IP address und of course the text itself should be stored in a variable (e. g. separated with an \n or just a space or tab after each block) and then be classified. The learning should also be done with all data availible.
+Saving the IP address is probably only meaningful for spam entries, because spammers often use the same IP address multiple times. In principle, you can leave out the IP of ham entries.

+

You can use b8 e. g. in a guestbook script and let it classify the text before saving it. Everyone has to decide which rating is necessary to classify a text as "spam", but a rating of >= 0.8 seems to be reasonable for me. If one expects the spam to be in another language that the ham entries or the spams are very short normally, one could also think about a limit of 0.7.
+The email filters out there mostly use > 0.9 or even > 0.99; but keep in mind that they have way more data to analyze in most of the cases. A guestbook entry may be quite short, especially when it's spam.

+

In my opinion, a autolearn function is very handy. I save spam messages with a rating higher than 0.7 but less than 0.9 automatically as spam. I don't do this with ham messages in an automated way to prevent the filter from saving a false negative as ham and then classifying and learning all the spam as ham when I'm on holidays ;-)

+
+
+

7   Closing

+

So … that's it. Thanks for using b8! If you find a bug or have an idea how to make b8 better, let me know. I'm also always looking forward to get e-mails from people using b8 on their homepages :-)

+
+
+

8   References

+ + + + + +
[2](1, 2) Paul Graham, A Plan For Spam (http://paulgraham.com/spam.html)
+ + + + + +
[3](1, 2, 3) Paul Graham, Better Bayesian Filtering (http://paulgraham.com/better.html)
+ + + + + +
[4](1, 2, 3, 4) Gary Robinson, Spam Detection (http://radio.weblogs.com/0101454/stories/2002/09/16/spamDetection.html)
+ + + + + +
[5]A Statistical Approach to the Spam Problem (http://linuxjournal.com/article/6467)
+ + + + + +
[6](1, 2, 3) Tobias Leupold, Statistical discussion about b8 (http://nasauber.de/opensource/b8/discussion/)
+
+
+

9   Appendix

+
+

9.1   FAQ

+
+

9.1.1   What about more than two categories?

+

I wrote b8 with the KISS principle in mind. For the "end-user", we have a class with almost no setup to do that can do three things: classify a text, learn a text and un-learn a text. Normally, there's no need to un-learn a text, so essentially, there are only two functions we need.
+This simplicity is only possible because b8 only knows two categories (normally "Ham" and "Spam" or some other category pair) and tells you, in one float number between 0 and 1, if a given texts rather fits in the first or the second category. If we would support multiple categories, more work would have to be done and things would become more complicated. One would have to setup the categories, have another database layout (perhaps making it mandatory to have SQL) and one float number would not be sufficient to describe b8's output, so more code would be needed – even outside of b8.

+

All the code, the database layout and particularly the math is intended to do exactly one thing: distinguish between two categories. I think it would be a lot of work to change b8 so that it would support more than two categories. Probably, this is possible to do, but don't ask me in which way we would have to change the math to get multiple-category support – I'm a dentist, not a mathematician ;-)
+Apart from this I do believe that most people using b8 don't want or need multiple categories. They just want to know if a text is spam or not, don't they? I do, at least ;-)

+

But let's think about the multiple-category thing. How would we calculate a rating for more than two categories? If we had a third one, let's call it "Treet", how would we calculate a rating? We could calculate three different ratings. One for "Ham", one for "Spam" and one for "Treet" and choose the highest one to tell the user what category fits best for the text. This could be done by using a small wrapper script using three instances of b8 as-is and three different databases, each containing texts being "Ham", "Spam", "Treet" and the respective counterparts.
+But here's the problem: if we have "Ham" and "Spam", "Spam" is the counterpart of "Ham". But what's the counterpart of "Spam" if we have more than one additional category? Where do the "Non-Ham", "Non-Spam" and "Non-Treet" texts come from?

+

Another approach, a direct calculation of more than two probabilities (the "Ham" probability is simply 1 minus the "Spam" probability, so we actually get two probabilities with the return value of b8) out of one database would require big changes in b8's structure and math.

+

There's a project called PHPNaiveBayesianFilter which supports multiple categories by default. The author calls his software "Version 1.0", but I think this is the very first release, not a stable or mature one. The most recent change of that release dates back to 2003 according to the "changed" date of the files inside the zip archive, so probably, this project is dead or has never been alive and under active development at all.
+Actually, I played around with that code but the results weren't really good, so I decided to write my own spam filter from scratch back in early 2006 ;-)

+

All in all, there seems to be no easy way to implement multiple (meaning more than two) categories using b8's current code base and probably, b8 will never support more than two categories. Perhaps, a fork or a complete re-write would be better than implementing such a feature. Anyway, I don't close my mind to multiple categories in b8. Feel free to tell me how multiple categories could be implementented in b8 or how a multiple-category version using the same code base (sharing a common abstract class?) could be written.

+
+
+

9.1.2   What about a list with words to ignore?

+

Some people suggested to introduce a list with words that b8 will simply ignore. Like "and", "or", "the", and so on. I don't think this is very meaningful.

+

First, it would just work for the particular language that has been stored in the list. Speaking of my homepage, most of my spam is English, almost all my ham is German. So I would have to maintain a list with the probably less interesting words for at least two languages. Additionally, I get spam in Chinese, Japanese and Cyrillic writing or something else I can't read as well. What word should be ignored in those texts?
+Second, why should we ever exclude words? Who tells us those words are actually meaningless? If a word appears both in ham and spam, it's rating will be near 0.5 and so, it won't be used for the final calculation if a appropriate minimum deviation was set. So b8 will exclude it anyway without any blacklist. And think of this: if we excluded a word of which we only think it doesn't mean anything but it actually does appear more often in ham or spam, the results will get even worse.

+

So why should we care about things we do not have to care about? ;-)

+
+
+

9.1.3   Why is it called "b8"?

+

The initial name for the filter was (damn creative!) "bayes-php". There were two main reasons for searching another name: 1. "bayes-php" sucks. 2. the PHP License says the PHP guys do not like when the name of a script written in PHP contains the word "PHP". Read the License FAQ for a reasonable argumentation about this.

+

Luckily, Tobias Lang proposed the new name "b8". And these are the reasons why I chose this name:

+
    +
  • "bayes-php" is a "b" followed by 8 letters.
  • +
  • "b8" is short and handy. Additionally, there was no program with the name "b8" or "bate"
  • +
  • The English verb "to bate" means "to decrease" – and that's what b8 does: it decreases the number of spam entries in your weblog or guestbook!
  • +
  • "b8" just sounds way cooler than "bayes-php" ;-)
  • +
+
+
+
+

9.2   About the database

+
+

9.2.1   The database layout

+

The database layout is quite simple. It's just key:value for everything stored. There are three "internal" variables stored as normal tokens (but all containing a * which is always used as a split character by the lexer, so we can't get collisions):

+
+
bayes*dbversion
+
This indicates the database's "version". The first versions of b8 did not set this. Version "2" indicates that we have a database created by a b8 version already storing the "lastseen" parameter.
+
bayes*texts.ham
+
The number of ham texts learned.
+
bayes*texts.spam
+
The number of spam texts learned.
+
+

Each "normal" token is stored with it's literal name as the key and it's data as the value. The data consists of the count of the token in all ham and spam texts and the date when the token was used the last time, all in one string and separated by spaces. So we have the following scheme:

+
+"token" => "count_ham count_spam lastseen"
+
+
+
+

9.2.2   The "lastseen" parameter

+

Somebody looking at the code might be wondering why b8 stores this "lastseen" parameter. This value is not used for any calculation at the moment. Initially, it was intended to keep the database maintainable in a way that "old" data could be removed. When e. g. a token only appeared once in ham or spam and has not been seen for a year, one could simply delete it from the database.
+I actually never used this feature (does anybody?). So probably, some changes will be done to this one day. Perhaps, I find a way to include this data in the spamminess calculation in a meaningful way, or at least for some statistics. One could also make this optional to keep the calculation effort small if this is needed.

+

Feel free to send me any suggestions about this!

+
+
+
+
+ + diff --git a/library/spam/doc/readme.rst b/library/spam/doc/readme.rst new file mode 100644 index 000000000..451b28326 --- /dev/null +++ b/library/spam/doc/readme.rst @@ -0,0 +1,371 @@ +========== +b8: readme +========== + +:Author: Tobias Leupold +:Homepage: http://nasauber.de/ +:Contact: tobias.leupold@web.de +:Date: |date| + +.. contents:: Table of Contents + +Description of b8 +================= + +What is b8? +----------- + +b8 is a spam filter implemented in `PHP `__. It is intended to keep your weblog or guestbook spam-free. The filter can be used anywhere in your PHP code and tells you whether a text is spam or not, using statistical text analysis. See `How does it work?`_ for details about this. To be able to do this, b8 first has to learn some spam and some ham example texts to decide what's good and what's not. If it makes mistakes classifying unknown texts, they can be corrected and b8 learns from the corrections, getting better with each learned text. + +At the moment of this writing, b8 has classified 14411 guestbook entries and weblog comments on my homepage since december 2006. 131 were ham. 39 spam texts (0.27 %) have been rated as ham (false negatives), with not even one false positive (ham message classified as spam). This results in a sensitivity of 99.73 % (the probability that a spam text will actually be rated as spam) and a specifity of 100 % (the probability that a ham text will actually be rated as ham) for me. I hope, you'll get the same good results :-) + +Basically, b8 is a statistical ("Bayesian"[#]_) spam filter like `Bogofilter `__ or `SpamBayes `__, but it is not intended to classify e-mails. When I started to write b8, I didn't find a good PHP spam filter (or any spam filter that wasn't just some example code how one *could* implement a Bayesian spam filter in PHP) that was intended to filter weblog or guestbook entries. That's why I had to write my own ;-) |br| +Caused by it's purpose, the way b8 works is slightly different from most of the Bayesian email spam filters out there. See `What's different?`_ if you're interested in the details. + +.. [#] A mathematician told me that the math in b8 actually does not use Bayes' theorem but some derived algorithms that are just related to it. So … let's simply believe that and stop claiming b8 was a *Bayesian* spam filter ;-) + +How does it work? +----------------- + +b8 basically uses the math and technique described in Paul Graham's article "A Plan For Spam" [#planforspam]_ to distinguish ham and spam. The improvements proposed in Graham's article "Better Bayesian Filtering" [#betterbayesian]_ and Gary Robinson's article "Spam Detection" [#spamdetection]_ have also been considered. See also the article "A Statistical Approach to the Spam Problem" [#statisticalapproach]_. + +b8 cuts the text to classify to pieces, extracting stuff like e-mail addresses, links and HTML tags. For each such token, it calculates a single probability for a text containing it being spam, based on what the filter has learned so far. When the token was not seen before, b8 tries to find similar ones using the "degeneration" described in [#betterbayesian]_ and uses the most relevant value found. If really nothing is found, b8 assumes a default rating for this token for the further calculations. |br| +Then, b8 takes the most relevant values (which have a rating far from 0.5, which would mean we don't know what it is) and calculates the probability that the whole text is spam by the inverse chi-square function described in [#spamdetection]_. +There are some parameters that can be set which influence the filter's behaviour (see below). + +In short words: you give b8 a text and it returns a value between 0 and 1, saying it's ham when it's near 0 and saying it's spam when it's near 1. + +What do I need for it? +---------------------- + +Not much! You just need PHP 5 on the server where b8 will be used (b8 version 0.5 finally dropped PHP 4 compatibility – thankfully ;-) and a proper storage possibility for the wordlists. I strongly recommend using `Berkeley DB `_. See below how you can check if you can use it and why you should use it. If the server's PHP wasn't compiled with Berkeley DB support, a `MySQL `_ table can be used alternatively. + +What's different? +----------------- + +b8 is designed to classify weblog or guestbook entries, not e-mails. For this reason, it uses a slightly different technique than most of the other statistical spam filters out there use. + +My experience was that spam entries on my weblog or guestbook were often quite short, sometimes just something like "123abc" as text and a link to a suspect homepage. Some spam bots don't even made a difference between e. g. the "name" and "text" fields and posted their text as email address, for example. Considering this, b8 just takes one string to classify, making no difference between "headers" and "text". |br| +The other thing is that most statistical spam filters count one token one time, no matter how often it appears in the text (as Graham describes it in [#planforspam]_). b8 does count how often a token was seen and learns or considers this. Additionally, the number of learned ham and spam texts are saved and used as the calculation base for the single probabilities. Why this? Because a text containing one link (no matter where it points to, just indicated by a "\h\t\t\p\:\/\/" or a "www.") might not be spam, but a text containing 20 links might be. + +This means that b8 might be good for classifying weblog or guestbook entries (I really think it is ;-) – but very likely, it will work quite poor when being used for something else (like classifying e-mails). But as said above, for this task, there are a lot of very good filters out there to choose from. + +Update from prior versions +========================== + +If this is a new b8 installation, read on at the `Installation`_ section! + +Update from bayes-php version 0.2.1 or earlier +---------------------------------------------- + +Please first follow the database update instructions of the bayes-php-0.3 release if you update from a version prior to bayes-php-0.3 and then read the following paragraph about updating from a version <0.3.3. + +Update from bayes-php version 0.3 or later +------------------------------------------ + +**You use Berkeley DB?** + Everything's fine, you can simply continue using your database. + +**You use MySQL?** + The ``CREATE`` statement of b8's wordlist has changed. The best is probably to create a dump via your favorite administration tool or script, create the new table and re-insert all data. The layout is still the same: there's one "token" column and one "data" column. Having done that, you can keep using your data. + +**You use SQLite?** + Sorry, at the moment, there's no SQLite backend for b8. But we're working on it :-) + +The configuration model of b8 has changed. Please read through the `Configuration`_ section and update your configuration accordingly. + +b8's lexer has been partially re-written. It should now be able to handle all kind of non-latin-1 input, like cyrillic, chinese or japanese texts. Caused by this fact, much more tokens will be recognized when classifying such texts. Therefore, you could get different results in b8's ratings, even if the same database is used and although the math is still the same. + +b8 0.5 introduced two constants that can be used in the ``learn()`` and ``unlearn()`` functions: ``b8::HAM`` and ``b8::SPAM``. The literal values "ham" and "spam" can still be used anyway. + +Installation +============ + +Installing b8 on your server is quite easy. You just have to provide the needed files. To do this, you could just upload the whole ``b8`` subdirectory to the base directory of your homepage. It contains the filter itself and all needed backend classes. The other directories (``doc``, ``example`` and ``install``) are not used by b8. + +That's it ;-) + +Configuration +============= + +The configuration is passed as arrays when instantiating a new b8 object. Two arrays can be passed to b8, one containing b8's base configuration and some settings for the lexer (which should be common for all lexer classes, in case some other lexer than the default one will be written one day) and one for the storage backend. |br| +You can have a look at ``example/index.php`` to see how this can be done. `Using b8 in your scripts`_ also shows example code showing how b8 can be included in a PHP script. + +Not all values have to be set. When some values are missing, the default ones will be used. If you do use the default settings, you don't have to pass them to b8. + +b8's base configuration +----------------------- + +All these values can be set in the "config_b8" array (the first parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the first argument. + +These are some basic settings telling b8 which backend classes to use: + + **storage** + This defines which storage backend will be used to save b8's wordlist. Currently, two backends are available: `Berkeley DB `_ (``dba``) and `MySQL `_ (``mysql``). At the moment, b8 does not support `SQLite `_ (as the previous version did), but it will be (hopefully) re-added in one of the next releases. The default is ``dba`` (string). + + *Berkeley DB* + This is the preferred storage backend. It was the original backend for the filter and remains the most performant. b8's storage model is optimized for this database, as it is really fast and fits perfectly to what the filter needs to do the job. All content is saved in a single file, you don't need special user rights or a database server. |br| + If you don't know whether your server's PHP can use a Berkeley DB, simply run the script ``install/setup_berkeleydb.php``. If it shows a Berkeley DB handler, please use this backend. + + *MySQL* + As some webspace hosters don't allow using a Berkeley DB (but please be sure to check if you can use it!), but most do provide a MySQL server, using a MySQL table for the wordlist is provided as an alternative storage method. As said above, b8 was always intended to use a Berkeley DB. It doesn't use or need SQL to query the database. So, very likely, this will work less performant, produce a lot of unnecessary overhead and waste computing power. But it will do fine anyway! + + See `Configuration of the storage backend`_ for the settings of the chosen backend. + + **degenerator** + The degenerator class to be used. See `How does it work?`_ and [#betterbayesian]_ if you're interested in what "degeneration" is. Defaults to ``default`` (string). At the moment, only one degenerator exists, so you probably don't want to change this unless you have written your own degenerator. + + **lexer** + The lexer class to be used. Defaults to ``default`` (string). At the moment, only one lexer exists, so you probably don't want to change this unless you have written your own lexer. + + The behaviour of the lexer can be additionally configured with the following variables: + + **min_size** + The minimal length for a token to be considered when calculating the rating of a text. Defaults to ``3`` (integer). + + **max_size** + The maximal length for a token to be considered when calculating the rating of a text. Defaults to ``30`` (integer). + + **allow_numbers** + Should pure numbers also be considered? Defaults to ``FALSE`` (boolean). + +The following settings influence the mathematical internals of b8. If you want to experiment, feel free to play around with them; but be warned: wrong settings of these values will result in poor performance or could even "short-circuit" the filter. |br| +Leave these values as they are unless you know what you are doing! + +The "Statistical discussion about b8" [#b8statistic]_ shows why the default values are the default ones. + + **use_relevant** + This tells b8 how many tokens should be used when calculating the spamminess of a text. The default setting is ``15`` (integer). This seems to be a quite reasonable value. When using to many tokens, the filter will fail on texts filled with useless stuff or with passages from a newspaper, etc. not being very spammish. |br| + The tokens counted multiple times (see above) are added in addition to this value. They don't replace other ratings. + + **min_dev** + This defines a minimum deviation from 0.5 that a token's rating must have to be considered when calculating the spamminess. Tokens with a rating closer to 0.5 than this value will simply be skipped. |br| + If you don't want to use this feature, set this to ``0``. Defaults to ``0.2`` (float). Read [#b8statistic]_ before increasing this. + + **rob_x** + This is Gary Robinson's *x* constant (cf. [#spamdetection]_). A completely unknown token will be rated with the value of ``rob_x``. The default ``0.5`` (float) seems to be quite reasonable, as we can't say if a token that also can't be rated by degeneration is good or bad. |br| + If you receive much more spam than ham or vice versa, you could change this setting accordingly. + + **rob_s** + This is Gary Robinson's *s* constant. This is essentially the probability that the *rob_x* value is correct for a completely unknown token. It will also shift the probability of rarely seen tokens towards this value. The default is ``0.3`` (float) |br| + See [#spamdetection]_ for a closer description of the *s* constant and read [#b8statistic]_ for specific information about this constant in b8's algorithms. + +Configuration of the storage backend +------------------------------------ + +All the following values can be set in the "config_database" array (the second parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the second argument. + +Settings for the Berkeley DB (DBA) backend +`````````````````````````````````````````` +**database** + The filename of the database file, relative to the location of ``b8.php``. Defaults to ``wordlist.db`` (string). + +**handler** + The DBA handler to use (cf. `the PHP documentation `_ and `Setting up a new Berkeley DB`_). Defaults to ``db4`` (string). + +Settings for the MySQL backend +`````````````````````````````` + +**database** + The database containing b8's wordlist table. Defaults to ``b8_wordlist`` (string). + +**table_name** + The table containing b8's wordlist. Defaults to ``b8_wordlist`` (string). + +**host** + The host of the MySQL server. Defaults to ``localhost`` (string). + +**user** + The user name used to open the database connection. Defaults to ``FALSE`` (boolean). + +**pass** + The password required to open the database connection. Defaults to ``FALSE`` (boolean). + +**connection** + An existing MySQL link-resource that can be used by b8. Defaults to ``NULL`` (NULL). + +Using b8 +======== + +Now, that everything is configured, you can start to use b8. A sample script that shows what can be done with the filter exists in ``example/index.php``. The best thing for testing how all this works is to use this script before using b8 in your own scripts. + +Before you can start, you have to setup a database so that b8 can store a wordlist. + +Setting up a new database +------------------------- + +Setting up a new Berkeley DB +```````````````````````````` + +I wrote a script to setup a new Berkeley DB for b8. It is located in ``install/setup_berkeleydb.php``. Just run this script on your server and be sure that the directory containing it has the proper access rights set so that the server's HTTP server user or PHP user can create a new file in it (probably ``0777``). The script is quite self-explaining, just run it. + +Of course, you can also create a Berkeley DB by hand. In this case, you just have to insert three keys: + +:: + + bayes*dbversion => 2 + bayes*texts.ham => 0 + bayes*texts.spam => 0 + +Be sure to set the right DBA handler in the storage backend configuration if it's not ``db4``. + +Setting up a new MySQL table +```````````````````````````` + +The SQL file ``install/setup_mysql.sql`` contains both the create statement for the wordlist table of b8 and the ``INSERT`` statements for adding the necessary internal variables. + +Simply change the table name according to your needs (or leave it as it is ;-) and run the SQL to setup a b8 wordlist MySQL table. + +Using b8 in your scripts +------------------------ + +Just have a look at the example script located in ``example/index.php`` to see how you can include b8 in your scripts. Essentially, this strips down to: + +:: + + # Include the b8 code + require "{$_SERVER['DOCUMENT_ROOT']}/b8/b8.php"; + + # Do some configuration + + $config_b8 = array( + 'some_key' => 'some_value', + 'foo' => 'bar' + ); + + $config_database = array( + 'some_key' => 'some_value', + 'foo' => 'bar' + ); + + # Create a new b8 instance + $b8 = new b8($config_b8, $config_database); + +b8 provides three functions in an object oriented way (called e. g. via ``$b8->classify($text)``): + +**learn($text, $category)** + This saves the reference text ``$text`` (string) in the category ``$category`` (b8 constant). |br| + b8 0.5 introduced two constants that can be used as ``$category``: ``b8::HAM`` and ``b8::SPAM``. To be downward compatible with older versions of b8, the literal values "ham" and "spam" (case-sensitive strings) can still be used here. + +**unlearn($text, $category)** + This function just exists to delete a text from a category in which is has been stored accidentally before. It deletes the reference text ``$text`` (string) from the category ``$category`` (either the constants ``b8::HAM`` or ``b8::SPAM`` or the literal case-sensitive strings "ham" or "spam" – cf. above). |br| + **Don't delete a spam text from ham after saving it in spam or vice versa, as long you don't have stored it accidentally in the wrong category before!** This will not improve performance, quite the opposite: it will actually break the filter after a time, as the counter for saved ham or spam texts will reach 0, although you have ham or spam tokens stored: the filter will try to remove texts from the ham or spam data which have never been stored there, decrease the counter for tokens which are found just skip the non-existing words. + +**classify($text)** + This function takes the text ``$text`` (string), calculates it's probability for being spam it and returns a value between 0 and 1 (float). |br| + A value close to 0 says the text is more likely ham and a value close to 1 says the text is more likely spam. What to do with this value is *your* business ;-) See also `Tips on operation`_ below. + +Tips on operation +================= + +Before b8 can decide whether a text is spam or ham, you have to tell it what you consider as spam or ham. At least one learned spam or one learned ham text is needed to calculate anything. To get good ratings, you need both learned ham and learned spam texts, the more the better. |br| +What's considered as "ham" or "spam" can be very different, depending on the operation site. On my homepage, practically each and every text posted in English or using cyrillic letters is spam. On an English or Russian homepage, this will be not the case. So I think it's not really meaningful to provide some "spam data" to start. Just train b8 with "your" spam and ham. + +For the practical use, I advise to give the filter all data availible. E. g. name, email address, homepage, IP address und of course the text itself should be stored in a variable (e. g. separated with an ``\n`` or just a space or tab after each block) and then be classified. The learning should also be done with all data availible. |br| +Saving the IP address is probably only meaningful for spam entries, because spammers often use the same IP address multiple times. In principle, you can leave out the IP of ham entries. + +You can use b8 e. g. in a guestbook script and let it classify the text before saving it. Everyone has to decide which rating is necessary to classify a text as "spam", but a rating of >= 0.8 seems to be reasonable for me. If one expects the spam to be in another language that the ham entries or the spams are very short normally, one could also think about a limit of 0.7. |br| +The email filters out there mostly use > 0.9 or even > 0.99; but keep in mind that they have way more data to analyze in most of the cases. A guestbook entry may be quite short, especially when it's spam. + +In my opinion, a autolearn function is very handy. I save spam messages with a rating higher than 0.7 but less than 0.9 automatically as spam. I don't do this with ham messages in an automated way to prevent the filter from saving a false negative as ham and then classifying and learning all the spam as ham when I'm on holidays ;-) + +Closing +======= + +So … that's it. Thanks for using b8! If you find a bug or have an idea how to make b8 better, let me know. I'm also always looking forward to get e-mails from people using b8 on their homepages :-) + +References +========== + +.. [#planforspam] Paul Graham, *A Plan For Spam* (http://paulgraham.com/spam.html) +.. [#betterbayesian] Paul Graham, *Better Bayesian Filtering* (http://paulgraham.com/better.html) +.. [#spamdetection] Gary Robinson, *Spam Detection* (http://radio.weblogs.com/0101454/stories/2002/09/16/spamDetection.html) +.. [#statisticalapproach] *A Statistical Approach to the Spam Problem* (http://linuxjournal.com/article/6467) +.. [#b8statistic] Tobias Leupold, *Statistical discussion about b8* (http://nasauber.de/opensource/b8/discussion/) + +Appendix +======== + +FAQ +--- + +What about more than two categories? +```````````````````````````````````` + +I wrote b8 with the `KISS principle `__ in mind. For the "end-user", we have a class with almost no setup to do that can do three things: classify a text, learn a text and un-learn a text. Normally, there's no need to un-learn a text, so essentially, there are only two functions we need. |br| +This simplicity is only possible because b8 only knows two categories (normally "Ham" and "Spam" or some other category pair) and tells you, in one float number between 0 and 1, if a given texts rather fits in the first or the second category. If we would support multiple categories, more work would have to be done and things would become more complicated. One would have to setup the categories, have another database layout (perhaps making it mandatory to have SQL) and one float number would not be sufficient to describe b8's output, so more code would be needed – even outside of b8. + +All the code, the database layout and particularly the math is intended to do exactly one thing: distinguish between two categories. I think it would be a lot of work to change b8 so that it would support more than two categories. Probably, this is possible to do, but don't ask me in which way we would have to change the math to get multiple-category support – I'm a dentist, not a mathematician ;-) |br| +Apart from this I do believe that most people using b8 don't want or need multiple categories. They just want to know if a text is spam or not, don't they? I do, at least ;-) + +But let's think about the multiple-category thing. How would we calculate a rating for more than two categories? If we had a third one, let's call it "`Treet `__", how would we calculate a rating? We could calculate three different ratings. One for "Ham", one for "Spam" and one for "Treet" and choose the highest one to tell the user what category fits best for the text. This could be done by using a small wrapper script using three instances of b8 as-is and three different databases, each containing texts being "Ham", "Spam", "Treet" and the respective counterparts. |br| +But here's the problem: if we have "Ham" and "Spam", "Spam" is the counterpart of "Ham". But what's the counterpart of "Spam" if we have more than one additional category? Where do the "Non-Ham", "Non-Spam" and "Non-Treet" texts come from? + +Another approach, a direct calculation of more than two probabilities (the "Ham" probability is simply 1 minus the "Spam" probability, so we actually get two probabilities with the return value of b8) out of one database would require big changes in b8's structure and math. + +There's a project called `PHPNaiveBayesianFilter `__ which supports multiple categories by default. The author calls his software "Version 1.0", but I think this is the very first release, not a stable or mature one. The most recent change of that release dates back to 2003 according to the "changed" date of the files inside the zip archive, so probably, this project is dead or has never been alive and under active development at all. |br| +Actually, I played around with that code but the results weren't really good, so I decided to write my own spam filter from scratch back in early 2006 ;-) + +All in all, there seems to be no easy way to implement multiple (meaning more than two) categories using b8's current code base and probably, b8 will never support more than two categories. Perhaps, a fork or a complete re-write would be better than implementing such a feature. Anyway, I don't close my mind to multiple categories in b8. Feel free to tell me how multiple categories could be implementented in b8 or how a multiple-category version using the same code base (sharing a common abstract class?) could be written. + +What about a list with words to ignore? +``````````````````````````````````````` + +Some people suggested to introduce a list with words that b8 will simply ignore. Like "and", "or", "the", and so on. I don't think this is very meaningful. + +First, it would just work for the particular language that has been stored in the list. Speaking of my homepage, most of my spam is English, almost all my ham is German. So I would have to maintain a list with the probably less interesting words for at least two languages. Additionally, I get spam in Chinese, Japanese and Cyrillic writing or something else I can't read as well. What word should be ignored in those texts? |br| +Second, why should we ever exclude words? Who tells us those words are *actually* meaningless? If a word appears both in ham and spam, it's rating will be near 0.5 and so, it won't be used for the final calculation if a appropriate minimum deviation was set. So b8 will exclude it anyway without any blacklist. And think of this: if we excluded a word of which we only *think* it doesn't mean anything but it actually does appear more often in ham or spam, the results will get even worse. + +So why should we care about things we do not have to care about? ;-) + + +Why is it called "b8"? +`````````````````````` + +The initial name for the filter was (damn creative!) "bayes-php". There were two main reasons for searching another name: 1. "bayes-php" sucks. 2. the `PHP License `_ says the PHP guys do not like when the name of a script written in PHP contains the word "PHP". Read the `License FAQ `_ for a reasonable argumentation about this. + +Luckily, `Tobias Lang `_ proposed the new name "b8". And these are the reasons why I chose this name: + +- "bayes-php" is a "b" followed by 8 letters. +- "b8" is short and handy. Additionally, there was no program with the name "b8" or "bate" +- The English verb "to bate" means "to decrease" – and that's what b8 does: it decreases the number of spam entries in your weblog or guestbook! +- "b8" just sounds way cooler than "bayes-php" ;-) + +About the database +------------------ + +The database layout +``````````````````` + +The database layout is quite simple. It's just key:value for everything stored. There are three "internal" variables stored as normal tokens (but all containing a ``*`` which is always used as a split character by the lexer, so we can't get collisions): + +**bayes*dbversion** + This indicates the database's "version". The first versions of b8 did not set this. Version "2" indicates that we have a database created by a b8 version already storing `the "lastseen" parameter`_. + +**bayes*texts.ham** + The number of ham texts learned. + +**bayes*texts.spam** + The number of spam texts learned. + +Each "normal" token is stored with it's literal name as the key and it's data as the value. The data consists of the count of the token in all ham and spam texts and the date when the token was used the last time, all in one string and separated by spaces. So we have the following scheme: + +:: + + "token" => "count_ham count_spam lastseen" + +The "lastseen" parameter +```````````````````````` + +Somebody looking at the code might be wondering why b8 stores this "lastseen" parameter. This value is not used for any calculation at the moment. Initially, it was intended to keep the database maintainable in a way that "old" data could be removed. When e. g. a token only appeared once in ham or spam and has not been seen for a year, one could simply delete it from the database. |br| +I actually never used this feature (does anybody?). So probably, some changes will be done to this one day. Perhaps, I find a way to include this data in the spamminess calculation in a meaningful way, or at least for some statistics. One could also make this optional to keep the calculation effort small if this is needed. + +Feel free to send me any suggestions about this! + +.. |br| raw:: html + +
+ +.. section-numbering:: + +.. |date| date:: diff --git a/library/spam/example/index.php b/library/spam/example/index.php new file mode 100644 index 000000000..6d3c14260 --- /dev/null +++ b/library/spam/example/index.php @@ -0,0 +1,241 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + + +### This is an example script demonstrating how b8 can be used. ### + +#/* + +# Use this code block if you want to use Berkeley DB. + +# The database filename is interpreted relative to the b8.php script location. + +$config_b8 = array( + 'storage' => 'dba' +); + +$config_database = array( + 'database' => 'wordlist.db', + 'handler' => 'db4' +); + +#*/ + +/* + +# Use this code block if you want to use MySQL. + +# An existing link resource can be passed to b8 by setting +# $config_database['connection'] to this link resource. +# Be sure to set your database access data otherwise! + +$config_b8 = array( + 'storage' => 'mysql' +); + +$config_database = array( + 'database' => 'test', + 'table_name' => 'b8_wordlist', + 'host' => 'localhost', + 'user' => '', + 'pass' => '' +); + +*/ + +# To be able to calculate the time the classification took + +$time_start = NULL; + +function microtimeFloat() +{ + list($usec, $sec) = explode(" ", microtime()); + return ((float) $usec + (float) $sec); +} + +# Output a nicely colored rating + +function formatRating($rating) +{ + + if($rating === FALSE) + return "could not calculate spaminess"; + + $red = floor(255 * $rating); + $green = floor(255 * (1 - $rating)); + + return "" . sprintf("%5f", $rating) . ""; + +} + +echo << + + + + + + + +example b8 interface + + + + + + + + + + +
+ +

example b8 interface

+ + +END; + +$postedText = ""; + +if(isset($_POST['action']) and $_POST['text'] == "") + echo "

Please type in a text!

\n\n"; + +elseif(isset($_POST['action']) and $_POST['text'] != "") { + + $time_start = microtimeFloat(); + + # Include the b8 code + require dirname(__FILE__) . "/../b8/b8.php"; + + # Create a new b8 instance + $b8 = new b8($config_b8, $config_database); + + # Check if everything worked smoothly + + $started_up = $b8->validate(); + + if($started_up !== TRUE) { + echo "example: Could not initialize b8. error code: $started_up"; + exit; + } + + $text = stripslashes($_POST['text']); + $postedText = htmlentities($text, ENT_QUOTES, 'UTF-8'); + + switch($_POST['action']) { + + case "Classify": + echo "

Spaminess: " . formatRating($b8->classify($text)) . "

\n"; + break; + + case "Save as Spam": + + $ratingBefore = $b8->classify($text); + $b8->learn($text, b8::SPAM); + $ratingAfter = $b8->classify($text); + + echo "

Saved the text as Spam

\n\n"; + + echo "
\n"; + echo "\n"; + echo "\n"; + echo "
Classification before learning:" . formatRating($ratingBefore) . "
Classification after learning:" . formatRating($ratingAfter) . "
\n\n"; + + break; + + case "Save as Ham": + + $ratingBefore = $b8->classify($text); + $b8->learn($text, b8::HAM); + $ratingAfter = $b8->classify($text); + + echo "

Saved the text as Ham

\n\n"; + + echo "
\n"; + echo "\n"; + echo "\n"; + echo "
Classification before learning:" . formatRating($ratingBefore) . "
Classification after learning:" . formatRating($ratingAfter) . "
\n\n"; + + break; + + case "Delete from Spam": + $b8->unlearn($text, b8::SPAM); + echo "

Deleted the text from Spam

\n\n"; + break; + + case "Delete from Ham": + $b8->unlearn($text, b8::HAM); + echo "

Deleted the text from Ham

\n\n"; + break; + + } + + $mem_used = round(memory_get_usage() / 1048576, 5); + $peak_mem_used = round(memory_get_peak_usage() / 1048576, 5); + $time_taken = round(microtimeFloat() - $time_start, 5); + +} + +echo << +
+
+ +
+ + + + + + + + + + + + +
+
+
+ + + +END; + +if($time_start !== NULL) { + +echo << + + + + +
Memory used: $mem_used MB
Peak memory used:$peak_mem_used MB
Time taken: $time_taken sec
+ + +END; + +} + +?> + + + + diff --git a/library/spam/install/setup_berkeleydb.php b/library/spam/install/setup_berkeleydb.php new file mode 100644 index 000000000..81e1d5afa --- /dev/null +++ b/library/spam/install/setup_berkeleydb.php @@ -0,0 +1,240 @@ + +# +# This file is part of the b8 package +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation in version 2.1 of the License. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +echo << + + + + + + + +b8 Berkeley DB setup + + + + + + + + + + +
+ +

b8 Berkeley DB setup

+ + +END; + +$failed = FALSE; + +if(isset($_POST['handler'])) { + + $dbfile = $_POST['dbfile']; + $dbfile_directory = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']); + + echo "

Creating database

\n\n"; + + echo "

\n"; + + echo "Checking database file name … "; + + if($dbfile == "") { + echo "Please provide the name of the database file!
\n"; + $failed = TRUE; + } + else + echo "$dbfile
\n"; + + if(!$failed) { + + echo "Touching/Creating " . htmlentities($dbfile) . " … "; + + if(touch($dbfile) === FALSE) { + echo "Failed to touch the database file. Please check the given filename and/or fix the permissions of $dbfile_directory.
\n"; + $failed = TRUE; + } + else + echo "done
\n"; + + } + + if(!$failed) { + + echo "Setting file permissions to 0666 &hellip "; + + if(chmod($dbfile, 0666) === FALSE) { + echo "Failed to change the permissions of $dbfile_directory/$dbfile. Please adjust them manually.
\n"; + $failed = TRUE; + } + else + echo "done
\n"; + + } + + if(!$failed) { + + echo "Checking if the given file is empty &hellip "; + + if(filesize($dbfile) > 0) { + echo "$dbfile_directory/$dbfile is not empty. Can't create a new database. Please delete/empty this file or give another filename.
\n"; + $failed = TRUE; + } + else + echo "it is
\n"; + + } + + if(!$failed) { + + echo "Connecting to $dbfile … "; + + $db = dba_open($dbfile, "c", $_POST['handler']); + + if($db === FALSE) { + echo "Could not connect to the database!
\n"; + $failed = TRUE; + } + else + echo "done
\n"; + + } + + if(!$failed) { + + echo "Storing necessary internal variables &hellip "; + + $internals = array( + "bayes*dbversion" => "2", + "bayes*texts.ham" => "0", + "bayes*texts.spam" => "0" + ); + + foreach($internals as $key => $value) { + if(dba_insert($key, $value, $db) === FALSE) { + echo "Failed to insert data!
\n"; + $failed = TRUE; + break; + } + } + + if(!$failed) + echo "done
\n"; + + } + + if(!$failed) { + + echo "Trying to read data from the database &hellip "; + + $dbversion = dba_fetch("bayes*dbversion", $db); + + if($dbversion != "2") { + echo "Failed to read data!
\n"; + $failed = TRUE; + } + else + echo "success
\n"; + } + + if(!$failed) { + + dba_close($db); + + echo "

\n\n"; + echo "

Successfully created a new b8 database!

\n\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "
Filename:$dbfile_directory/$dbfile
DBA handler:{$_POST['handler']}
\n\n"; + echo "

Move this file to it's destination directory (default: the base directory of b8) to use it with b8. Be sure to use the right DBA handler in b8's configuration."; + + } + + echo "

\n\n"; + +} + +if($failed === TRUE or !isset($_POST['handler'])) { + +echo << + +

DBA Handler

+ +

+The following table shows all available DBA handlers. Please choose the "Berkeley DB" one. +

+ + + + +END; + +foreach(dba_handlers(TRUE) as $name => $version) { + + $checked = ""; + + if(!isset($_POST['handler'])) { + if(strpos($version, "Berkeley") !== FALSE ) + $checked = " checked=\"checked\""; + } + else { + if($_POST['handler'] == $name) + $checked = " checked=\"checked\""; + } + + echo "\n"; + +} + +echo << + +

Database file

+ +

+Please the name of the desired database file. It will be created in the directory where this script is located. +

+ +

+ +

+ +

+ +

+ + + + +END; + +} + +?> + + + + + + diff --git a/library/spam/install/setup_mysql.sql b/library/spam/install/setup_mysql.sql new file mode 100644 index 000000000..ac43274e9 --- /dev/null +++ b/library/spam/install/setup_mysql.sql @@ -0,0 +1,27 @@ + +-- Copyright (C) 2010 Tobias Leupold +-- +-- This file is part of the b8 package +-- +-- This program is free software; you can redistribute it and/or modify it +-- under the terms of the GNU Lesser General Public License as published by +-- the Free Software Foundation in version 2.1 of the License. +-- +-- This program is distributed in the hope that it will be useful, but +-- WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +-- License for more details. +-- +-- You should have received a copy of the GNU Lesser General Public License +-- along with this program; if not, write to the Free Software Foundation, +-- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +CREATE TABLE `b8_wordlist` ( + `token` varchar(255) character set utf8 collate utf8_bin NOT NULL, + `count` varchar(255) default NULL, + PRIMARY KEY (`token`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +INSERT INTO `b8_wordlist` VALUES ('bayes*dbversion', '2'); +INSERT INTO `b8_wordlist` VALUES ('bayes*texts.ham', '0'); +INSERT INTO `b8_wordlist` VALUES ('bayes*texts.spam', '0');
HandlerDescription
$name$version