1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
|
<?php
/* Copyright (C) 2006-2019 Tobias Leupold <tobias.leupold@gmx.de>
b8 - A statistical ("Bayesian") spam filter written in PHP
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 b8 spam filter library
*
* @license LGPL 2.1
* @package b8
* @author Tobias Leupold <tobias.leupold@gmx.de>
* @author Oliver Lillie <ollie@buggedcom.co.uk> (original PHP 5 port)
*/
namespace b8;
spl_autoload_register(
function ($class) {
$parts = explode('\\', $class);
if ($parts[0] === 'b8') // In kalkun, we want this autoloader to load only classes for b8
{
require_once __DIR__ . DIRECTORY_SEPARATOR . $parts[1]
. DIRECTORY_SEPARATOR . $parts[2] . '.php';
}
}
);
class b8
{
const DBVERSION = 3;
const SPAM = 'spam';
const HAM = 'ham';
const LEARN = 'learn';
const UNLEARN = 'unlearn';
const CLASSIFIER_TEXT_MISSING = 'CLASSIFIER_TEXT_MISSING';
const TRAINER_TEXT_MISSING = 'TRAINER_TEXT_MISSING';
const TRAINER_CATEGORY_MISSING = 'TRAINER_CATEGORY_MISSING';
const TRAINER_CATEGORY_FAIL = 'TRAINER_CATEGORY_FAIL';
const INTERNALS_TEXTS = 'b8*texts';
const INTERNALS_DBVERSION = 'b8*dbversion';
const KEY_DB_VERSION = 'dbversion';
const KEY_COUNT_HAM = 'count_ham';
const KEY_COUNT_SPAM = 'count_spam';
const KEY_TEXTS_HAM = 'texts_ham';
const KEY_TEXTS_SPAM = 'texts_spam';
private $config = [ 'lexer' => 'standard',
'degenerator' => 'standard',
'storage' => 'dba',
'use_relevant' => 15,
'min_dev' => 0.2,
'rob_s' => 0.3,
'rob_x' => 0.5 ];
private $storage = null;
private $lexer = null;
private $degenerator = null;
private $token_data = null;
/**
* Constructs b8
*
* @access public
* @param array b8's configuration: [ 'lexer' => string,
'degenerator' => string,
'storage' => string,
'use_relevant' => int,
'min_dev' => float,
'rob_s' => float,
'rob_x' => float ]
* @param array The storage backend's config (depending on the backend used)
* @param array The lexer's config (depending on the lexer used)
* @param array The degenerator's config (depending on the degenerator used)
* @return void
*/
function __construct(array $config = [],
array $config_storage = [],
array $config_lexer = [],
array $config_degenerator = [])
{
// Validate config data
foreach ($config as $name => $value) {
switch ($name) {
case 'min_dev':
case 'rob_s':
case 'rob_x':
$this->config[$name] = (float) $value;
break;
case 'use_relevant':
$this->config[$name] = (int) $value;
break;
case 'lexer':
case 'degenerator':
case 'storage':
$this->config[$name] = (string) $value;
break;
default:
throw new \Exception(b8::class . ": Unknown configuration key: \"$name\"");
}
}
// Setup the degenerator class
$class = '\\b8\\degenerator\\' . $this->config['degenerator'];
$this->degenerator = new $class($config_degenerator);
// Setup the lexer class
$class = '\\b8\\lexer\\' . $this->config['lexer'];
$this->lexer = new $class($config_lexer);
// Setup the storage backend
$class = '\\b8\\storage\\' . $this->config['storage'];
$this->storage = new $class($config_storage, $this->degenerator);
}
/**
* Classifies a text
*
* @access public
* @param string The text to classify
* @return mixed float The rating between 0 (ham) and 1 (spam) or an error code
*/
public function classify($text = null)
{
// Let's first see if the user called the function correctly
if ($text === null) {
return \b8\b8::CLASSIFIER_TEXT_MISSING;
}
// 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->storage->get_internals();
// Calculate the spaminess 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 available data for the token set from the database
$this->token_data = $this->storage->get(array_keys($tokens));
// Calculate the spaminess and importance for each token (or a degenerated form of it)
$word_count = [];
$rating = [];
$importance = [];
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);
$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 = [];
for ($i = 0; $i < $this->config['use_relevant']; $i++) {
if ($token = key($importance)) {
// Important tokens remain
// If the token's rating is relevant enough, use it
if (abs(0.5 - $rating[$token]) > $this->config['min_dev']) {
// Tokens that appear more than once also count more than once
for ($x = 0, $l = $word_count[$token]; $x < $l; $x++) {
array_push($relevant, $rating[$token]);
}
}
} else {
// We have less words as we want to use, so we already use what we have and can
// break here
break;
}
next($importance);
}
// Calculate the spaminess of the text (thanks to Mr. Robinson ;-)
// We set both haminess and spaminess to 1 for the first multiplying
$haminess = 1;
$spaminess = 1;
// Consider all relevant ratings
foreach ($relevant as $value) {
$haminess *= (1.0 - $value);
$spaminess *= $value;
}
// If no token was good for calculation, we really don't know how to rate this text, so
// we can return 0.5 without further calculations.
if ($haminess == 1 && $spaminess == 1) {
return 0.5;
}
// Calculate the combined rating
// Get the number of relevant ratings
$n = count($relevant);
// The actual haminess and spaminess
$haminess = 1 - pow($haminess, (1 / $n));
$spaminess = 1 - pow($spaminess, (1 / $n));
// Calculate the combined indicator
$probability = ($haminess - $spaminess) / ($haminess + $spaminess);
// 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 spaminess of a single token also considering "degenerated" versions
*
* @access private
* @param string The word to rate
* @param array The "internals" array
* @return float The word's rating
*/
private function get_probability($word, array $internals)
{
// Let's see what we have!
if (isset($this->token_data['tokens'][$word])) {
// The token is in the database, so we can use it's data as-is and calculate the
// spaminess of this token directly
return $this->calculate_probability($this->token_data['tokens'][$word], $internals);
}
// The token was not found, so do we at least have similar words?
if (isset($this->token_data['degenerates'][$word])) {
// We found similar words, so calculate the spaminess 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->calculate_probability($count, $internals);
// 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 spaminess calculation of a single token
*
* @access private
* @param array The token's data [ \b8\b8::KEY_COUNT_HAM => int,
\b8\b8::KEY_COUNT_SPAM => int ]
* @param array The "internals" array
* @return float The rating
*/
private function calculate_probability(array $data, array $internals)
{
// Calculate the basic probability as proposed 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 spaminess because we count tokens
// appearing multiple times not just once but as often as they appear in the learned texts.
$rel_ham = $data[\b8\b8::KEY_COUNT_HAM];
$rel_spam = $data[\b8\b8::KEY_COUNT_SPAM];
if ($internals[\b8\b8::KEY_TEXTS_HAM] > 0) {
$rel_ham = $data[\b8\b8::KEY_COUNT_HAM] / $internals[\b8\b8::KEY_TEXTS_HAM];
}
if ($internals[\b8\b8::KEY_TEXTS_SPAM] > 0) {
$rel_spam = $data[\b8\b8::KEY_COUNT_SPAM] / $internals[\b8\b8::KEY_TEXTS_SPAM];
}
$rating = $rel_spam / ($rel_ham + $rel_spam);
// Calculate the better probability proposed by Mr. Robinson
$all = $data[\b8\b8::KEY_COUNT_HAM] + $data[\b8\b8::KEY_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 The category
* @return void
*/
private function check_category($category)
{
return $category === \b8\b8::HAM || $category === \b8\b8::SPAM;
}
/**
* Learn a reference text
*
* @access public
* @param string The text to learn
* @param string Either b8::SPAM or b8::HAM
* @return mixed void or an error code
*/
public function learn($text = null, $category = null)
{
// Let's first see if the user called the function correctly
if ($text === null) {
return \b8\b8::TRAINER_TEXT_MISSING;
}
if ($category === null) {
return \b8\b8::TRAINER_CATEGORY_MISSING;
}
return $this->process_text($text, $category, \b8\b8::LEARN);
}
/**
* Unlearn a reference text
*
* @access public
* @param string The text to unlearn
* @param string Either b8::SPAM or b8::HAM
* @return mixed void or an error code
*/
public function unlearn($text = null, $category = null)
{
// Let's first see if the user called the function correctly
if ($text === null) {
return \b8\b8::TRAINER_TEXT_MISSING;
}
if ($category === null) {
return \b8\b8::TRAINER_CATEGORY_MISSING;
}
return $this->process_text($text, $category, \b8\b8::UNLEARN);
}
/**
* Does the actual interaction with the storage backend for learning or unlearning texts
*
* @access private
* @param string The text to process
* @param string Either b8::SPAM or b8::HAM
* @param string Either b8::LEARN or b8::UNLEARN
* @return mixed void or an error code
*/
private function process_text($text, $category, $action)
{
// Look if the request is okay
if (! $this->check_category($category)) {
return \b8\b8::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->storage->process_text($tokens, $category, $action);
}
}
|