From 4168d47ecd9235e3d14c45766244cf45f80b3e15 Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 26 Mar 2017 05:29:24 +0000 Subject: [PATCH 1/5] Issue 3248: Make communityhome work again. --- mod/community.php | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/mod/community.php b/mod/community.php index 1743304010..45326e291d 100644 --- a/mod/community.php +++ b/mod/community.php @@ -1,12 +1,12 @@ ' . t('Community') . ''; - if(! $update) { + if (! $update) { nav_set_selected('community'); } - if(x($a->data,'search')) + if (x($a->data,'search')) { $search = notags(trim($a->data['search'])); - else + } else { $search = ((x($_GET,'search')) ? notags(trim(rawurldecode($_GET['search']))) : ''); - + } // Here is the way permissions work in this module... // Only public posts can be shown @@ -55,7 +51,7 @@ function community_content(App $a, $update = 0) { return $o; } - $maxpostperauthor = get_config('system','max_author_posts_community_page'); + $maxpostperauthor = Config::get('system','max_author_posts_community_page'); if ($maxpostperauthor != 0) { $count = 1; @@ -65,23 +61,24 @@ function community_content(App $a, $update = 0) { do { foreach ($r AS $row=>$item) { - if ($previousauthor == $item["author-link"]) + if ($previousauthor == $item["author-link"]) { ++$numposts; - else + } else { $numposts = 0; - + } $previousauthor = $item["author-link"]; - if (($numposts < $maxpostperauthor) AND (sizeof($s) < $a->pager['itemspage'])) + if (($numposts < $maxpostperauthor) AND (sizeof($s) < $a->pager['itemspage'])) { $s[] = $item; + } } - if ((sizeof($s) < $a->pager['itemspage'])) + if ((sizeof($s) < $a->pager['itemspage'])) { $r = community_getitems($a->pager['start'] + ($count * $a->pager['itemspage']), $a->pager['itemspage']); - + } } while ((sizeof($s) < $a->pager['itemspage']) AND (++$count < 50) AND (sizeof($r) > 0)); - } else + } else { $s = $r; - + } // we behave the same in message lists as the search module $o .= conversation($a, $s, 'community', $update); @@ -92,9 +89,9 @@ function community_content(App $a, $update = 0) { } function community_getitems($start, $itemspage) { - if (get_config('system','community_page_style') == CP_GLOBAL_COMMUNITY) + if (Config::get('system','community_page_style') == CP_GLOBAL_COMMUNITY) { return(community_getpublicitems($start, $itemspage)); - + } $r = qu("SELECT %s FROM `thread` INNER JOIN `user` ON `user`.`uid` = `thread`.`uid` AND NOT `user`.`hidewall` From 92f531532092737f0747efb9e1a497f19b9734aa Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 26 Mar 2017 12:51:25 +0000 Subject: [PATCH 2/5] We now return basic system data via nodeinfo at every time. --- mod/nodeinfo.php | 271 ++++++++++++++++++++++++----------------------- 1 file changed, 136 insertions(+), 135 deletions(-) diff --git a/mod/nodeinfo.php b/mod/nodeinfo.php index 6f20494757..5415bac481 100644 --- a/mod/nodeinfo.php +++ b/mod/nodeinfo.php @@ -5,15 +5,13 @@ * Documentation: http://nodeinfo.diaspora.software/schema.html */ -require_once("include/plugin.php"); +use \Friendica\Core\Config; + +require_once('include/plugin.php'); function nodeinfo_wellknown(App $a) { - if (!get_config("system", "nodeinfo")) { - http_status_exit(404); - killme(); - } - $nodeinfo = array("links" => array(array("rel" => "http://nodeinfo.diaspora.software/ns/schema/1.0", - "href" => App::get_baseurl()."/nodeinfo/1.0"))); + $nodeinfo = array('links' => array(array('rel' => 'http://nodeinfo.diaspora.software/ns/schema/1.0', + 'href' => App::get_baseurl().'/nodeinfo/1.0'))); header('Content-type: application/json; charset=utf-8'); echo json_encode($nodeinfo, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); @@ -21,124 +19,127 @@ function nodeinfo_wellknown(App $a) { } function nodeinfo_init(App $a) { - if (!get_config("system", "nodeinfo")) { + if (!Config::get('system', 'nodeinfo')) { http_status_exit(404); killme(); } - if (($a->argc != 2) OR ($a->argv[1] != "1.0")) { + if (($a->argc != 2) OR ($a->argv[1] != '1.0')) { http_status_exit(404); killme(); } - $smtp = (function_exists("imap_open") AND !get_config("system","imap_disabled") AND !get_config("system","dfrn_only")); + $smtp = (function_exists('imap_open') AND !Config::get('system', 'imap_disabled') AND !Config::get('system', 'dfrn_only')); $nodeinfo = array(); - $nodeinfo["version"] = "1.0"; - $nodeinfo["software"] = array("name" => "friendica", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION); + $nodeinfo['version'] = '1.0'; + $nodeinfo['software'] = array('name' => 'friendica', 'version' => FRIENDICA_VERSION.'-'.DB_UPDATE_VERSION); - $nodeinfo["protocols"] = array(); - $nodeinfo["protocols"]["inbound"] = array(); - $nodeinfo["protocols"]["outbound"] = array(); + $nodeinfo['protocols'] = array(); + $nodeinfo['protocols']['inbound'] = array(); + $nodeinfo['protocols']['outbound'] = array(); - if (get_config("system","diaspora_enabled")) { - $nodeinfo["protocols"]["inbound"][] = "diaspora"; - $nodeinfo["protocols"]["outbound"][] = "diaspora"; + if (Config::get('system', 'diaspora_enabled')) { + $nodeinfo['protocols']['inbound'][] = 'diaspora'; + $nodeinfo['protocols']['outbound'][] = 'diaspora'; } - $nodeinfo["protocols"]["inbound"][] = "friendica"; - $nodeinfo["protocols"]["outbound"][] = "friendica"; + $nodeinfo['protocols']['inbound'][] = 'friendica'; + $nodeinfo['protocols']['outbound'][] = 'friendica'; - if (!get_config("system","ostatus_disabled")) { - $nodeinfo["protocols"]["inbound"][] = "gnusocial"; - $nodeinfo["protocols"]["outbound"][] = "gnusocial"; + if (!Config::get('system', 'ostatus_disabled')) { + $nodeinfo['protocols']['inbound'][] = 'gnusocial'; + $nodeinfo['protocols']['outbound'][] = 'gnusocial'; } - $nodeinfo["services"] = array(); - $nodeinfo["services"]["inbound"] = array(); - $nodeinfo["services"]["outbound"] = array(); + $nodeinfo['services'] = array(); + $nodeinfo['services']['inbound'] = array(); + $nodeinfo['services']['outbound'] = array(); - $nodeinfo["openRegistrations"] = ($a->config['register_policy'] != 0); + $nodeinfo['usage'] = array(); - $nodeinfo["usage"] = array(); - $nodeinfo["usage"]["users"] = array("total" => (int)get_config("nodeinfo","total_users"), - "activeHalfyear" => (int)get_config("nodeinfo","active_users_halfyear"), - "activeMonth" => (int)get_config("nodeinfo","active_users_monthly")); - $nodeinfo["usage"]["localPosts"] = (int)get_config("nodeinfo","local_posts"); - $nodeinfo["usage"]["localComments"] = (int)get_config("nodeinfo","local_comments"); + $nodeinfo['openRegistrations'] = ($a->config['register_policy'] != 0); - $nodeinfo["metadata"] = array("nodeName" => $a->config["sitename"]); + $nodeinfo['metadata'] = array('nodeName' => $a->config['sitename']); - if (plugin_enabled("appnet")) - $nodeinfo["services"]["inbound"][] = "appnet"; + if (Config::get('system', 'nodeinfo')) { - if (plugin_enabled("appnet") OR plugin_enabled("buffer")) - $nodeinfo["services"]["outbound"][] = "appnet"; + $nodeinfo['usage']['users'] = array('total' => (int)Config::get('nodeinfo', 'total_users'), + 'activeHalfyear' => (int)Config::get('nodeinfo', 'active_users_halfyear'), + 'activeMonth' => (int)Config::get('nodeinfo', 'active_users_monthly')); + $nodeinfo['usage']['localPosts'] = (int)Config::get('nodeinfo', 'local_posts'); + $nodeinfo['usage']['localComments'] = (int)Config::get('nodeinfo', 'local_comments'); - if (plugin_enabled("blogger")) - $nodeinfo["services"]["outbound"][] = "blogger"; + if (plugin_enabled('appnet')) { + $nodeinfo['services']['inbound'][] = 'appnet'; + } + if (plugin_enabled('appnet') OR plugin_enabled('buffer')) { + $nodeinfo['services']['outbound'][] = 'appnet'; + } + if (plugin_enabled('blogger')) { + $nodeinfo['services']['outbound'][] = 'blogger'; + } + if (plugin_enabled('dwpost')) { + $nodeinfo['services']['outbound'][] = 'dreamwidth'; + } + if (plugin_enabled('fbpost') OR plugin_enabled('buffer')) { + $nodeinfo['services']['outbound'][] = 'facebook'; + } + if (plugin_enabled('statusnet')) { + $nodeinfo['services']['inbound'][] = 'gnusocial'; + $nodeinfo['services']['outbound'][] = 'gnusocial'; + } - if (plugin_enabled("dwpost")) - $nodeinfo["services"]["outbound"][] = "dreamwidth"; + if (plugin_enabled('gpluspost') OR plugin_enabled('buffer')) { + $nodeinfo['services']['outbound'][] = 'google'; + } + if (plugin_enabled('ijpost')) { + $nodeinfo['services']['outbound'][] = 'insanejournal'; + } + if (plugin_enabled('libertree')) { + $nodeinfo['services']['outbound'][] = 'libertree'; + } + if (plugin_enabled('buffer')) { + $nodeinfo['services']['outbound'][] = 'linkedin'; + } + if (plugin_enabled('ljpost')) { + $nodeinfo['services']['outbound'][] = 'livejournal'; + } + if (plugin_enabled('buffer')) { + $nodeinfo['services']['outbound'][] = 'pinterest'; + } + if (plugin_enabled('posterous')) { + $nodeinfo['services']['outbound'][] = 'posterous'; + } + if (plugin_enabled('pumpio')) { + $nodeinfo['services']['inbound'][] = 'pumpio'; + $nodeinfo['services']['outbound'][] = 'pumpio'; + } - if (plugin_enabled("fbpost") OR plugin_enabled("buffer")) - $nodeinfo["services"]["outbound"][] = "facebook"; + if ($smtp) { + $nodeinfo['services']['outbound'][] = 'smtp'; + } + if (plugin_enabled('tumblr')) { + $nodeinfo['services']['outbound'][] = 'tumblr'; + } + if (plugin_enabled('twitter') OR plugin_enabled('buffer')) { + $nodeinfo['services']['outbound'][] = 'twitter'; + } + if (plugin_enabled('wppost')) { + $nodeinfo['services']['outbound'][] = 'wordpress'; + } + $nodeinfo['metadata']['protocols'] = $nodeinfo['protocols']; + $nodeinfo['metadata']['protocols']['outbound'][] = 'atom1.0'; + $nodeinfo['metadata']['protocols']['inbound'][] = 'atom1.0'; + $nodeinfo['metadata']['protocols']['inbound'][] = 'rss2.0'; - if (plugin_enabled("statusnet")) { - $nodeinfo["services"]["inbound"][] = "gnusocial"; - $nodeinfo["services"]["outbound"][] = "gnusocial"; + $nodeinfo['metadata']['services'] = $nodeinfo['services']; + + if (plugin_enabled('twitter')) { + $nodeinfo['metadata']['services']['inbound'][] = 'twitter'; + } } - if (plugin_enabled("gpluspost") OR plugin_enabled("buffer")) - $nodeinfo["services"]["outbound"][] = "google"; - - if (plugin_enabled("ijpost")) - $nodeinfo["services"]["outbound"][] = "insanejournal"; - - if (plugin_enabled("libertree")) - $nodeinfo["services"]["outbound"][] = "libertree"; - - if (plugin_enabled("buffer")) - $nodeinfo["services"]["outbound"][] = "linkedin"; - - if (plugin_enabled("ljpost")) - $nodeinfo["services"]["outbound"][] = "livejournal"; - - if (plugin_enabled("buffer")) - $nodeinfo["services"]["outbound"][] = "pinterest"; - - if (plugin_enabled("posterous")) - $nodeinfo["services"]["outbound"][] = "posterous"; - - if (plugin_enabled("pumpio")) { - $nodeinfo["services"]["inbound"][] = "pumpio"; - $nodeinfo["services"]["outbound"][] = "pumpio"; - } - - // redmatrix - - if ($smtp) - $nodeinfo["services"]["outbound"][] = "smtp"; - - if (plugin_enabled("tumblr")) - $nodeinfo["services"]["outbound"][] = "tumblr"; - - if (plugin_enabled("twitter") OR plugin_enabled("buffer")) - $nodeinfo["services"]["outbound"][] = "twitter"; - - if (plugin_enabled("wppost")) - $nodeinfo["services"]["outbound"][] = "wordpress"; - - $nodeinfo["metadata"]["protocols"] = $nodeinfo["protocols"]; - $nodeinfo["metadata"]["protocols"]["outbound"][] = "atom1.0"; - $nodeinfo["metadata"]["protocols"]["inbound"][] = "atom1.0"; - $nodeinfo["metadata"]["protocols"]["inbound"][] = "rss2.0"; - - $nodeinfo["metadata"]["services"] = $nodeinfo["services"]; - - if (plugin_enabled("twitter")) - $nodeinfo["metadata"]["services"]["inbound"][] = "twitter"; - header('Content-type: application/json; charset=utf-8'); echo json_encode($nodeinfo, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); exit; @@ -150,40 +151,40 @@ function nodeinfo_cron() { $a = get_app(); - // If the plugin "statistics_json" is enabled then disable it and actrivate nodeinfo. - if (plugin_enabled("statistics_json")) { - set_config("system", "nodeinfo", true); + // If the plugin 'statistics_json' is enabled then disable it and actrivate nodeinfo. + if (plugin_enabled('statistics_json')) { + Config::set('system', 'nodeinfo', true); - $plugin = "statistics_json"; - $plugins = get_config("system","addon"); + $plugin = 'statistics_json'; + $plugins = Config::get('system', 'addon'); $plugins_arr = array(); - if($plugins) { - $plugins_arr = explode(",",str_replace(" ", "",$plugins)); + if ($plugins) { + $plugins_arr = explode(',',str_replace(' ', '',$plugins)); $idx = array_search($plugin, $plugins_arr); - if ($idx !== false){ + if ($idx !== false) { unset($plugins_arr[$idx]); uninstall_plugin($plugin); - set_config("system","addon", implode(", ",$plugins_arr)); + Config::set('system', 'addon', implode(', ',$plugins_arr)); } } } - if (!get_config("system", "nodeinfo")) + if (!Config::get('system', 'nodeinfo')) { return; + } + $last = Config::get('nodeinfo', 'last_calucation'); - $last = get_config('nodeinfo','last_calucation'); - - if($last) { + if ($last) { // Calculate every 24 hours $next = $last + (24 * 60 * 60); - if($next > time()) { - logger("calculation intervall not reached"); + if ($next > time()) { + logger('calculation intervall not reached'); return; } } - logger("cron_start"); + logger('cron_start'); $users = qu("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item` FROM `user` @@ -202,31 +203,31 @@ function nodeinfo_cron() { foreach ($users AS $user) { if ((strtotime($user['login_date']) > $halfyear) OR - (strtotime($user['last-item']) > $halfyear)) + (strtotime($user['last-item']) > $halfyear)) { ++$active_users_halfyear; - + } if ((strtotime($user['login_date']) > $month) OR - (strtotime($user['last-item']) > $month)) + (strtotime($user['last-item']) > $month)) { ++$active_users_monthly; - + } } - set_config('nodeinfo','total_users', $total_users); - logger("total_users: ".$total_users, LOGGER_DEBUG); + Config::set('nodeinfo', 'total_users', $total_users); + logger('total_users: '.$total_users, LOGGER_DEBUG); - set_config('nodeinfo','active_users_halfyear', $active_users_halfyear); - set_config('nodeinfo','active_users_monthly', $active_users_monthly); + Config::set('nodeinfo', 'active_users_halfyear', $active_users_halfyear); + Config::set('nodeinfo', 'active_users_monthly', $active_users_monthly); } $posts = qu("SELECT COUNT(*) AS local_posts FROM `thread` WHERE `thread`.`wall` AND `thread`.`uid` != 0"); - if (!is_array($posts)) + if (!is_array($posts)) { $local_posts = -1; - else - $local_posts = $posts[0]["local_posts"]; + } else { + $local_posts = $posts[0]['local_posts']; + } + Config::set('nodeinfo', 'local_posts', $local_posts); - set_config('nodeinfo','local_posts', $local_posts); - - logger("local_posts: ".$local_posts, LOGGER_DEBUG); + logger('local_posts: '.$local_posts, LOGGER_DEBUG); $posts = qu("SELECT COUNT(*) FROM `contact` INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `item`.`uid` = `contact`.`uid` AND @@ -234,21 +235,21 @@ function nodeinfo_cron() { WHERE `contact`.`self`", dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_DFRN)); - if (!is_array($posts)) + if (!is_array($posts)) { $local_comments = -1; - else - $local_comments = $posts[0]["local_comments"]; - - set_config('nodeinfo','local_comments', $local_comments); + } else { + $local_comments = $posts[0]['local_comments']; + } + Config::set('nodeinfo', 'local_comments', $local_comments); // Now trying to register - $url = "http://the-federation.info/register/".$a->get_hostname(); + $url = 'http://the-federation.info/register/'.$a->get_hostname(); logger('registering url: '.$url, LOGGER_DEBUG); $ret = fetch_url($url); logger('registering answer: '.$ret, LOGGER_DEBUG); - logger("cron_end"); - set_config('nodeinfo','last_calucation', time()); + logger('cron_end'); + Config::set('nodeinfo', 'last_calucation', time()); } ?> From 8fe1fc2f5236c66b8e9f1dd8f187da8529592e5d Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 26 Mar 2017 13:12:02 +0000 Subject: [PATCH 3/5] Remove parendingsdas --- mod/nodeinfo.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mod/nodeinfo.php b/mod/nodeinfo.php index 5415bac481..7f010cee41 100644 --- a/mod/nodeinfo.php +++ b/mod/nodeinfo.php @@ -7,7 +7,7 @@ use \Friendica\Core\Config; -require_once('include/plugin.php'); +require_once 'include/plugin.php'; function nodeinfo_wellknown(App $a) { $nodeinfo = array('links' => array(array('rel' => 'http://nodeinfo.diaspora.software/ns/schema/1.0', From a06bbd809a272979e36e4e43bdbb482e53bebb4f Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 26 Mar 2017 14:06:26 +0000 Subject: [PATCH 4/5] The "spam" libary is not in use, so we remove it completely --- library/spam/README | 12 - library/spam/b8/b8.php | 503 ------------- library/spam/b8/b8.php.ORIG | 503 ------------- .../b8/degenerator/degenerator_default.php | 127 ---- library/spam/b8/lexer/lexer_default.php | 205 ----- library/spam/b8/storage/storage_base.php | 396 ---------- library/spam/b8/storage/storage_base.php.ORIG | 395 ---------- library/spam/b8/storage/storage_dba.php | 198 ----- library/spam/b8/storage/storage_frndc.php | 313 -------- 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 - 17 files changed, 5272 deletions(-) delete mode 100644 library/spam/README delete mode 100644 library/spam/b8/b8.php delete mode 100644 library/spam/b8/b8.php.ORIG delete mode 100644 library/spam/b8/degenerator/degenerator_default.php delete mode 100644 library/spam/b8/lexer/lexer_default.php delete mode 100644 library/spam/b8/storage/storage_base.php delete mode 100644 library/spam/b8/storage/storage_base.php.ORIG delete mode 100644 library/spam/b8/storage/storage_dba.php delete mode 100644 library/spam/b8/storage/storage_frndc.php delete mode 100644 library/spam/b8/storage/storage_mysql.php delete mode 100644 library/spam/doc/COPYING delete mode 100644 library/spam/doc/ChangeLog delete mode 100644 library/spam/doc/readme.htm delete mode 100644 library/spam/doc/readme.rst delete mode 100644 library/spam/example/index.php delete mode 100644 library/spam/install/setup_berkeleydb.php delete mode 100644 library/spam/install/setup_mysql.sql diff --git a/library/spam/README b/library/spam/README deleted file mode 100644 index a0d67fca71..0000000000 --- a/library/spam/README +++ /dev/null @@ -1,12 +0,0 @@ -B8 for Friendica - -B8 is an excellent bayesian spam implementation for PHP. However when evaluating it for use in Friendica there were a few shortcomings. B8's primary audience is guestbooks and blogs - single user situations. - -Friendica is a multi-user distributed social environment. So the first thing we need to add to b8 is a concept of user ID. - -Second we don't want to use a second stored set of DB login credentials so we're going to implemetn Friendica's MySQL driver and use our existing connection and credentials. - -The third requirement is that the B8 processing model is to load a set of word/data sets from the DB, perform processing (which may change the value of the data) and then store the results back to the DB. We're in a highly dynamic environment with lots of sometimes concurrent message processing. So the plan is to alter the storage architecture to read data in, do processing, and then apply a somewhat atomic change operation where the changes are performed in a single query using the current data in storage rather than something passed through outside processing and where the data may be outdated come time to store it. - -In accordance with the LGPL of the B8 package these changes are available in source form at http://github.com/friendica/friendica in the directory library/spam - \ No newline at end of file diff --git a/library/spam/b8/b8.php b/library/spam/b8/b8.php deleted file mode 100644 index 28a3dd29f9..0000000000 --- a/library/spam/b8/b8.php +++ /dev/null @@ -1,503 +0,0 @@ - -# -# 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($uid,$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($uid); - - # 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),$uid); - - # 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, $uid) - { - return $this->_process_text($text, $category, self::LEARN, $uid); - } - - /** - * 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, $uid) - { - return $this->_process_text($text, $category, self::UNLEARN, $uid); - } - - /** - * 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, $uid = 0) - { - - # 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, $uid); - - } - -} - -?> \ No newline at end of file diff --git a/library/spam/b8/b8.php.ORIG b/library/spam/b8/b8.php.ORIG deleted file mode 100644 index ea1e15ffad..0000000000 --- a/library/spam/b8/b8.php.ORIG +++ /dev/null @@ -1,503 +0,0 @@ - -# -# 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 deleted file mode 100644 index 4ff6d882b7..0000000000 --- a/library/spam/b8/degenerator/degenerator_default.php +++ /dev/null @@ -1,127 +0,0 @@ - -# -# 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 deleted file mode 100644 index 7b5ca22bfb..0000000000 --- a/library/spam/b8/lexer/lexer_default.php +++ /dev/null @@ -1,205 +0,0 @@ - -# -# 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 deleted file mode 100644 index 6b181ee96e..0000000000 --- a/library/spam/b8/storage/storage_base.php +++ /dev/null @@ -1,396 +0,0 @@ - -# -# 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($uid) - { - - $internals = $this->get_internals($uid); - - 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($uid) - { - - $internals = $this->_get_query( - array( - self::INTERNALS_TEXTS_HAM, - self::INTERNALS_TEXTS_SPAM, - self::INTERNALS_DBVERSION - ), - $uid - ); - - 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, $uid) - { - - # 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, $uid); - - # 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'], $uid ); - - } - - 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'], $uid); - - } - - } - - } - - } - - # 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, $uid) - { - - # 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($uid); - - # Then, fetch all data for all tokens we have (and update their lastseen parameters) - $token_data = $this->_get_query(array_keys($tokens), $uid); - - # 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'], $uid); - else - $this->_del($token, $uid); - - } - - 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, $uid); - - } - - } - - } - - # 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'], $uid); - } - - elseif($category === b8::SPAM) { - $internals['texts_spam']++; - $this->_update(self::INTERNALS_TEXTS_SPAM, $internals['texts_spam'], $uid); - } - - } - - 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'], $uid); - - } - - 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'], $uid); - - } - - } - - # We're done and can commit all changes to the database now - $this->_commit($uid); - - } - -} - -?> \ No newline at end of file diff --git a/library/spam/b8/storage/storage_base.php.ORIG b/library/spam/b8/storage/storage_base.php.ORIG deleted file mode 100644 index 01f5a69d72..0000000000 --- a/library/spam/b8/storage/storage_base.php.ORIG +++ /dev/null @@ -1,395 +0,0 @@ - -# -# 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 deleted file mode 100644 index 04618b23ef..0000000000 --- a/library/spam/b8/storage/storage_dba.php +++ /dev/null @@ -1,198 +0,0 @@ - -# -# 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_frndc.php b/library/spam/b8/storage/storage_frndc.php deleted file mode 100644 index e01e652ae4..0000000000 --- a/library/spam/b8/storage/storage_frndc.php +++ /dev/null @@ -1,313 +0,0 @@ - -# -# 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_frndc 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(); - private $uid = 0; - - 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() - { - - $this->connected = TRUE; - return TRUE; - - } - - /** - * 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, $uid) - { - - // Construct the query ... - if (count($tokens) > 0) { - - $where = array(); - - foreach ($tokens as $token) { - $token = dbesc($token); - array_push($where, $token); - } - - $where = 'term IN ("' . implode('", "', $where) . '")'; - } else { - $token = dbesc($token); - $where = 'term = "' . $token . '"'; - } - - // ... and fetch the data - - $result = q('SELECT * FROM `spam` WHERE ' . $where . ' AND `uid` = ' . $uid ); - - - $returned_tokens = array(); - if (dbm::is_result($result)) { - foreach ($result as $rr) { - $returned_tokens[] = $rr['term']; - } - } - $to_create = array(); - - if (count($tokens) > 0) { - foreach($tokens as $token) - if(! in_array($token,$returned_tokens)) - $to_create[] = str_tolower($token); - } - if (count($to_create)) { - $sql = ''; - foreach ($to_create as $term) { - if (strlen($sql)) { - $sql .= ','; - } - $sql .= sprintf("(`term`,`datetime`,`uid`) VALUES('%s','%s',%d)", - dbesc(str_tolower($term)), - dbesc(datetime_convert()), - intval($uid) - ); - } - q("INSERT INTO `spam` " . $sql); - } - - return $result; - - } - - /** - * Store a token to the database. - * - * @access protected - * @param string $token - * @param string $count - * @return void - */ - protected function _put($token, $count, $uid) { - $token = dbesc($token); - $count = dbesc($count); - $uid = dbesc($uid); - array_push($this->_puts, '("' . $token . '", "' . $count . '", "' . $uid .'")'); - } - - /** - * Update an existing token. - * - * @access protected - * @param string $token - * @param string $count - * @return void - */ - protected function _update($token, $count, $uid) - { - $token = dbesc($token); - $count = dbesc($count); - $uid = dbesc($uid); - array_push($this->_puts, '("' . $token . '", "' . $count . '", "' . $uid .'")'); - } - - /** - * Remove a token from the database. - * - * @access protected - * @param string $token - * @return void - */ - protected function _del($token, $uid) - { - $token = dbesc($token); - $uid = dbesc($uid); - $this->uid = $uid; - array_push($this->_deletes, $token); - } - - /** - * Commits any modification queries. - * - * @access protected - * @return void - */ - protected function _commit($uid) - { - - if(count($this->_deletes) > 0) { - - $result = q(' - DELETE FROM ' . $this->config['table_name'] . ' - WHERE token IN ("' . implode('", "', $this->_deletes) . '") AND uid = ' . $this->uid); - - $this->_deletes = array(); - - } - - if(count($this->_puts) > 0) { - - $result = q(' - INSERT INTO ' . $this->config['table_name'] . '(token, count, uid) - VALUES ' . implode(', ', $this->_puts)); - - $this->_puts = array(); - - } - - if(count($this->_updates) > 0) { - - // this still needs work - $result = q("select * from " . $this->config['table_name'] . ' where token = '); - - - $result = q(' - INSERT INTO ' . $this->config['table_name'] . '(token, count, uid) - VALUES ' . implode(', ', $this->_updates) . ', ' . $uid . ' - ON DUPLICATE KEY UPDATE ' . $this->config['table_name'] . '.count = VALUES(count);', $this->_connection); - - $this->_updates = array(); - - } - - } - -} diff --git a/library/spam/b8/storage/storage_mysql.php b/library/spam/b8/storage/storage_mysql.php deleted file mode 100644 index 0225363509..0000000000 --- a/library/spam/b8/storage/storage_mysql.php +++ /dev/null @@ -1,351 +0,0 @@ - -# -# 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 deleted file mode 100644 index 8add30ad59..0000000000 --- a/library/spam/doc/COPYING +++ /dev/null @@ -1,504 +0,0 @@ - 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 deleted file mode 100644 index 78a4fc77fc..0000000000 --- a/library/spam/doc/ChangeLog +++ /dev/null @@ -1,179 +0,0 @@ -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 deleted file mode 100644 index 727d5ae5fe..0000000000 --- a/library/spam/doc/readme.htm +++ /dev/null @@ -1,707 +0,0 @@ - - - - - - -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 deleted file mode 100644 index 451b28326b..0000000000 --- a/library/spam/doc/readme.rst +++ /dev/null @@ -1,371 +0,0 @@ -========== -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 deleted file mode 100644 index 6d3c142602..0000000000 --- a/library/spam/example/index.php +++ /dev/null @@ -1,241 +0,0 @@ - -# -# 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 deleted file mode 100644 index 81e1d5afac..0000000000 --- a/library/spam/install/setup_berkeleydb.php +++ /dev/null @@ -1,240 +0,0 @@ - -# -# 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 deleted file mode 100644 index ac43274e91..0000000000 --- a/library/spam/install/setup_mysql.sql +++ /dev/null @@ -1,27 +0,0 @@ - --- 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'); From 68cfe9c7feab46c697c13b6f154c1d61083d7ae5 Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 26 Mar 2017 14:19:34 +0000 Subject: [PATCH 5/5] library/oauth.php is not in use as well. --- library/oauth.php | 728 ---------------------------------------------- 1 file changed, 728 deletions(-) delete mode 100644 library/oauth.php diff --git a/library/oauth.php b/library/oauth.php deleted file mode 100644 index caf1a08395..0000000000 --- a/library/oauth.php +++ /dev/null @@ -1,728 +0,0 @@ - , - // "expires" => , - // "scope" => , - // "redirect_uri" => , - // "expires" => , - // "scope" => - // ) - // - // Return null if the code is invalid. - - return null; - } - - // Take the provided authorization code values and store them somewhere (db, etc.) - // Required for AUTH_CODE_GRANT_TYPE - protected function store_auth_code($code, $client_id, $redirect_uri, $expires, $scope) { - // This function should be the storage counterpart to get_stored_auth_code - - // If storage fails for some reason, we're not currently checking - // for any sort of success/failure, so you should bail out of the - // script and provide a descriptive fail message - } - - // Grant access tokens for basic user credentials - // IETF Draft 4.1.2: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.2 - // Required for USER_CREDENTIALS_GRANT_TYPE - protected function check_user_credentials($client_id, $username, $password) { - // Check the supplied username and password for validity - // You can also use the $client_id param to do any checks required - // based on a client, if you need that - // If the username and password are invalid, return false - - // If the username and password are valid, and you want to verify the scope of - // a user's access, return an array with the scope values, like so: - // - // array ( - // "scope" => - // ) - // - // We'll check the scope you provide against the requested scope before - // providing an access token. - // - // Otherwise, just return true. - - return false; - } - - // Grant access tokens for assertions - // IETF Draft 4.1.3: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.3 - // Required for ASSERTION_GRANT_TYPE - protected function check_assertion($client_id, $assertion_type, $assertion) { - // Check the supplied assertion for validity - // You can also use the $client_id param to do any checks required - // based on a client, if you need that - // If the assertion is invalid, return false - - // If the assertion is valid, and you want to verify the scope of - // an access request, return an array with the scope values, like so: - // - // array ( - // "scope" => - // ) - // - // We'll check the scope you provide against the requested scope before - // providing an access token. - // - // Otherwise, just return true. - - return false; - } - - // Grant refresh access tokens - // IETF Draft 4.1.4: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.4 - // Required for REFRESH_TOKEN_GRANT_TYPE - protected function get_refresh_token($refresh_token) { - // Retrieve the stored data for the given refresh token - // Should return: - // - // array ( - // "client_id" => , - // "expires" => , - // "scope" => - // ) - // - // Return null if the token id is invalid. - - return null; - } - - // Store refresh access tokens - // Required for REFRESH_TOKEN_GRANT_TYPE - protected function store_refresh_token($token, $client_id, $expires, $scope = null) { - // If storage fails for some reason, we're not currently checking - // for any sort of success/failure, so you should bail out of the - // script and provide a descriptive fail message - - return; - } - - // Grant access tokens for the "none" grant type - // Not really described in the IETF Draft, so I just left a method stub...do whatever you want! - // Required for NONE_GRANT_TYPE - protected function check_none_access($client_id) { - return false; - } - - protected function get_default_authentication_realm() { - // Change this to whatever authentication realm you want to send in a WWW-Authenticate header - return "Service"; - } - - /* End stuff that should get overridden */ - - private $access_token_lifetime = 3600; - private $auth_code_lifetime = 30; - private $refresh_token_lifetime = 1209600; // Two weeks - - public function __construct($access_token_lifetime = 3600, $auth_code_lifetime = 30, $refresh_token_lifetime = 1209600) { - $this->access_token_lifetime = $access_token_lifetime; - $this->auth_code_lifetime = $auth_code_lifetime; - $this->refresh_token_lifetime = $refresh_token_lifetime; - } - - /* Resource protecting (Section 5) */ - - // Check that a valid access token has been provided - // - // The scope parameter defines any required scope that the token must have - // If a scope param is provided and the token does not have the required scope, - // we bounce the request - // - // Some implementations may choose to return a subset of the protected resource - // (i.e. "public" data) if the user has not provided an access token - // or if the access token is invalid or expired - // - // The IETF spec says that we should send a 401 Unauthorized header and bail immediately - // so that's what the defaults are set to - // - // Here's what each parameter does: - // $scope = A space-separated string of required scope(s), if you want to check for scope - // $exit_not_present = If true and no access token is provided, send a 401 header and exit, otherwise return false - // $exit_invalid = If true and the implementation of get_access_token returns null, exit, otherwise return false - // $exit_expired = If true and the access token has expired, exit, otherwise return false - // $exit_scope = If true the access token does not have the required scope(s), exit, otherwise return false - // $realm = If you want to specify a particular realm for the WWW-Authenticate header, supply it here - public function verify_access_token($scope = null, $exit_not_present = true, $exit_invalid = true, $exit_expired = true, $exit_scope = true, $realm = null) { - $token_param = $this->get_access_token_param(); - if ($token_param === false) // Access token was not provided - return $exit_not_present ? $this->send_401_unauthorized($realm, $scope) : false; - - // Get the stored token data (from the implementing subclass) - $token = $this->get_access_token($token_param); - if ($token === null) - return $exit_invalid ? $this->send_401_unauthorized($realm, $scope, ERROR_INVALID_TOKEN) : false; - - // Check token expiration (I'm leaving this check separated, later we'll fill in better error messages) - if (isset($token["expires"]) && time() > $token["expires"]) - return $exit_expired ? $this->send_401_unauthorized($realm, $scope, ERROR_EXPIRED_TOKEN) : false; - - // Check scope, if provided - // If token doesn't have a scope, it's null/empty, or it's insufficient, then throw an error - if ($scope && - (!isset($token["scope"]) || !$token["scope"] || !$this->check_scope($scope, $token["scope"]))) - return $exit_scope ? $this->send_401_unauthorized($realm, $scope, ERROR_INSUFFICIENT_SCOPE) : false; - - return true; - } - - - // Returns true if everything in required scope is contained in available scope - // False if something in required scope is not in available scope - private function check_scope($required_scope, $available_scope) { - // The required scope should match or be a subset of the available scope - if (!is_array($required_scope)) - $required_scope = explode(" ", $required_scope); - - if (!is_array($available_scope)) - $available_scope = explode(" ", $available_scope); - - return (count(array_diff($required_scope, $available_scope)) == 0); - } - - // Send a 401 unauthorized header with the given realm - // and an error, if provided - private function send_401_unauthorized($realm, $scope, $error = null) { - $realm = $realm === null ? $this->get_default_authentication_realm() : $realm; - - $auth_header = "WWW-Authenticate: Token realm='".$realm."'"; - - if ($scope) - $auth_header .= ", scope='".$scope."'"; - - if ($error !== null) - $auth_header .= ", error='".$error."'"; - - header("HTTP/1.1 401 Unauthorized"); - header($auth_header); - - exit; - } - - // Pulls the access token out of the HTTP request - // Either from the Authorization header or GET/POST/etc. - // Returns false if no token is present - // TODO: Support POST or DELETE - private function get_access_token_param() { - $auth_header = $this->get_authorization_header(); - - if ($auth_header !== false) { - // Make sure only the auth header is set - if (isset($_GET[OAUTH_TOKEN_PARAM_NAME]) || isset($_POST[OAUTH_TOKEN_PARAM_NAME])) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - $auth_header = trim($auth_header); - - // Make sure it's Token authorization - if (strcmp(substr($auth_header, 0, 6),"Token ") !== 0) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - // Parse the rest of the header - if (preg_match('/\s*token\s*="(.+)"/', substr($auth_header, 6), $matches) == 0 || count($matches) < 2) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - return $matches[1]; - } - - if (isset($_GET[OAUTH_TOKEN_PARAM_NAME])) { - if (isset($_POST[OAUTH_TOKEN_PARAM_NAME])) // Both GET and POST are not allowed - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - return $_GET[OAUTH_TOKEN_PARAM_NAME]; - } - - if (isset($_POST[OAUTH_TOKEN_PARAM_NAME])) - return $_POST[OAUTH_TOKEN_PARAM_NAME]; - - return false; - } - - /* Access token granting (Section 4) */ - - // Grant or deny a requested access token - // This would be called from the "/token" endpoint as defined in the spec - // Obviously, you can call your endpoint whatever you want - public function grant_access_token() { - $filters = array( - "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_TOKEN_GRANT_TYPE), "flags" => FILTER_REQUIRE_SCALAR), - "scope" => array("flags" => FILTER_REQUIRE_SCALAR), - "code" => array("flags" => FILTER_REQUIRE_SCALAR), - "redirect_uri" => array("filter" => FILTER_VALIDATE_URL, "flags" => array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_REQUIRE_SCALAR)), - "username" => array("flags" => FILTER_REQUIRE_SCALAR), - "password" => array("flags" => FILTER_REQUIRE_SCALAR), - "assertion_type" => array("flags" => FILTER_REQUIRE_SCALAR), - "assertion" => array("flags" => FILTER_REQUIRE_SCALAR), - "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR), - ); - - $input = filter_input_array(INPUT_POST, $filters); - - // Grant Type must be specified. - if (!$input["grant_type"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - // Make sure we've implemented the requested grant type - if (!in_array($input["grant_type"], $this->get_supported_grant_types())) - $this->error(ERROR_BAD_REQUEST, ERROR_UNSUPPORTED_GRANT_TYPE); - - // Authorize the client - $client = $this->get_client_credentials(); - - if ($this->auth_client_credentials($client[0], $client[1]) === false) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS); - - if (!$this->authorize_client($client[0], $input["grant_type"])) - $this->error(ERROR_BAD_REQUEST, ERROR_UNAUTHORIZED_CLIENT); - - // Do the granting - switch ($input["grant_type"]) { - case AUTH_CODE_GRANT_TYPE: - if (!$input["code"] || !$input["redirect_uri"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - $stored = $this->get_stored_auth_code($input["code"]); - - if ($stored === null || $input["redirect_uri"] != $stored["redirect_uri"] || $client[0] != $stored["client_id"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); - - if ($stored["expires"] > time()) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); - - break; - case USER_CREDENTIALS_GRANT_TYPE: - if (!$input["username"] || !$input["password"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - $stored = $this->check_user_credentials($client[0], $input["username"], $input["password"]); - - if ($stored === false) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); - - break; - case ASSERTION_GRANT_TYPE: - if (!$input["assertion_type"] || !$input["assertion"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - $stored = $this->check_assertion($client[0], $input["assertion_type"], $input["assertion"]); - - if ($stored === false) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); - - break; - case REFRESH_TOKEN_GRANT_TYPE: - if (!$input["refresh_token"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - $stored = $this->get_refresh_token($input["refresh_token"]); - - if ($stored === null || $client[0] != $stored["client_id"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); - - if ($stored["expires"] > time()) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); - - break; - case NONE_GRANT_TYPE: - $stored = $this->check_none_access($client[0]); - - if ($stored === false) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - } - - // Check scope, if provided - if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->check_scope($input["scope"], $stored["scope"]))) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_SCOPE); - - if (!$input["scope"]) - $input["scope"] = null; - - $token = $this->create_access_token($client[0], $input["scope"]); - - $this->send_json_headers(); - echo json_encode($token); - } - - // Internal function used to get the client credentials from HTTP basic auth or POST data - // See http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-2 - private function get_client_credentials() { - if (isset($_SERVER["PHP_AUTH_USER"]) && $_POST && isset($_POST["client_id"])) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS); - - // Try basic auth - if (isset($_SERVER["PHP_AUTH_USER"])) - return array($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]); - - // Try POST - if ($_POST && isset($_POST["client_id"])) { - if (isset($_POST["client_secret"])) - return array($_POST["client_id"], $_POST["client_secret"]); - - return array($_POST["client_id"], NULL); - } - - // No credentials were specified - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS); - } - - /* End-user/client Authorization (Section 3 of IETF Draft) */ - - // Pull the authorization request data out of the HTTP request - // and return it so the authorization server can prompt the user - // for approval - public function get_authorize_params() { - $filters = array( - "client_id" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_CLIENT_ID), "flags" => FILTER_REQUIRE_SCALAR), - "response_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_AUTH_RESPONSE_TYPE), "flags" => FILTER_REQUIRE_SCALAR), - "redirect_uri" => array("filter" => FILTER_VALIDATE_URL, "flags" => array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_REQUIRE_SCALAR)), - "state" => array("flags" => FILTER_REQUIRE_SCALAR), - "scope" => array("flags" => FILTER_REQUIRE_SCALAR), - ); - - $input = filter_input_array(INPUT_GET, $filters); - - // Make sure a valid client id was supplied - if (!$input["client_id"]) { - if ($input["redirect_uri"]) - $this->callback_error($input["redirect_uri"], ERROR_INVALID_CLIENT_ID, $input["state"]); - - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_ID); // We don't have a good URI to use - } - - // redirect_uri is not required if already established via other channels - // check an existing redirect URI against the one supplied - $redirect_uri = $this->get_redirect_uri($input["client_id"]); - - // At least one of: existing redirect URI or input redirect URI must be specified - if (!$redirect_uri && !$input["redirect_uri"]) - $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); - - // get_redirect_uri should return false if the given client ID is invalid - // this probably saves us from making a separate db call, and simplifies the method set - if ($redirect_uri === false) - $this->callback_error($input["redirect_uri"], ERROR_INVALID_CLIENT_ID, $input["state"]); - - // If there's an existing uri and one from input, verify that they match - if ($redirect_uri && $input["redirect_uri"]) { - // Ensure that the input uri starts with the stored uri - if (strcasecmp(substr($input["redirect_uri"], 0, strlen($redirect_uri)),$redirect_uri) !== 0) - $this->callback_error($input["redirect_uri"], ERROR_REDIRECT_URI_MISMATCH, $input["state"]); - } elseif ($redirect_uri) { // They did not provide a uri from input, so use the stored one - $input["redirect_uri"] = $redirect_uri; - } - - // type and client_id are required - if (!$input["response_type"]) - $this->callback_error($input["redirect_uri"], ERROR_INVALID_REQUEST, $input["state"], ERROR_INVALID_RESPONSE_TYPE); - - // Check requested auth response type against the list of supported types - if (array_search($input["response_type"], $this->get_supported_auth_response_types()) === false) - $this->callback_error($input["redirect_uri"], ERROR_UNSUPPORTED_RESPONSE_TYPE, $input["state"]); - - // Validate that the requested scope is supported - if ($input["scope"] && !$this->check_scope($input["scope"], $this->get_supported_scopes())) - $this->callback_error($input["redirect_uri"], ERROR_INVALID_SCOPE, $input["state"]); - - return $input; - } - - // After the user has approved or denied the access request - // the authorization server should call this function to redirect - // the user appropriately - - // The params all come from the results of get_authorize_params - // except for $is_authorized -- this is true or false depending on whether - // the user authorized the access - public function finish_client_authorization($is_authorized, $type, $client_id, $redirect_uri, $state, $scope = null) { - if ($state !== null) - $result["query"]["state"] = $state; - - if ($is_authorized === false) { - $result["query"]["error"] = ERROR_USER_DENIED; - } else { - if ($type == AUTH_CODE_AUTH_RESPONSE_TYPE || $type == CODE_AND_TOKEN_AUTH_RESPONSE_TYPE) - $result["query"]["code"] = $this->create_auth_code($client_id, $redirect_uri, $scope); - - if ($type == ACCESS_TOKEN_AUTH_RESPONSE_TYPE || $type == CODE_AND_TOKEN_AUTH_RESPONSE_TYPE) - $result["fragment"] = $this->create_access_token($client_id, $scope); - } - - $this->do_redirect_uri_callback($redirect_uri, $result); - } - - /* Other/utility functions */ - - private function do_redirect_uri_callback($redirect_uri, $result) { - header("HTTP/1.1 302 Found"); - header("Location: " . $this->build_uri($redirect_uri, $result)); - exit; - } - - private function build_uri($uri, $data) { - $parse_url = parse_url($uri); - - // Add our data to the parsed uri - foreach ($data as $k => $v) { - if (isset($parse_url[$k])) - $parse_url[$k] .= "&" . http_build_query($v); - else - $parse_url[$k] = http_build_query($v); - } - - // Put humpty dumpty back together - return - ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "") - .((isset($parse_url["user"])) ? $parse_url["user"] . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") ."@" : "") - .((isset($parse_url["host"])) ? $parse_url["host"] : "") - .((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "") - .((isset($parse_url["path"])) ? $parse_url["path"] : "") - .((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "") - .((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : ""); - } - - // This belongs in a separate factory, but to keep it simple, I'm just keeping it here. - private function create_access_token($client_id, $scope) { - $token = array( - "access_token" => $this->gen_access_token(), - "expires_in" => $this->access_token_lifetime, - "scope" => $scope - ); - - $this->store_access_token($token["access_token"], $client_id, time() + $this->access_token_lifetime, $scope); - - // Issue a refresh token also, if we support them - if (in_array(REFRESH_TOKEN_GRANT_TYPE, $this->get_supported_grant_types())) { - $token["refresh_token"] = $this->gen_access_token(); - $this->store_refresh_token($token["refresh_token"], $client_id, time() + $this->refresh_token_lifetime, $scope); - } - - return $token; - } - - private function create_auth_code($client_id, $redirect_uri, $scope) { - $code = $this->gen_auth_code(); - $this->store_auth_code($code, $client_id, $redirect_uri, time() + $this->auth_code_lifetime, $scope); - return $code; - } - - // Implementing classes may want to override these two functions - // to implement other access token or auth code generation schemes - private function gen_access_token() { - return base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand())); - } - - private function gen_auth_code() { - return base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand())); - } - - // Implementing classes may need to override this function for use on non-Apache web servers - // Just pull out the Authorization HTTP header and return it - // Return false if the Authorization header does not exist - private function get_authorization_header() { - if (array_key_exists("HTTP_AUTHORIZATION", $_SERVER)) - return $_SERVER["HTTP_AUTHORIZATION"]; - - if (function_exists("apache_request_headers")) { - $headers = apache_request_headers(); - - if (array_key_exists("Authorization", $headers)) - return $headers["Authorization"]; - } - - return false; - } - - private function send_json_headers() { - header("Content-Type: application/json"); - header("Cache-Control: no-store"); - } - - public function error($code, $message = null) { - header("HTTP/1.1 " . $code); - - if ($message) { - $this->send_json_headers(); - echo json_encode(array("error" => $message)); - } - - exit; - } - - public function callback_error($redirect_uri, $error, $state, $message = null, $error_uri = null) { - $result["query"]["error"] = $error; - - if ($state) - $result["query"]["state"] = $state; - - if ($message) - $result["query"]["error_description"] = $message; - - if ($error_uri) - $result["query"]["error_uri"] = $error_uri; - - $this->do_redirect_uri_callback($redirect_uri, $result); - } -} \ No newline at end of file
HandlerDescription
$name$version