filters.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. <?php
  2. /**
  3. * Message and Spam Filter Plugin - Filtering Functions
  4. *
  5. * @copyright 1999-2025 The SquirrelMail Project Team
  6. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  7. * @version $Id$
  8. * @package plugins
  9. * @subpackage filters
  10. */
  11. // TODO: This plugin has an issue that seems to corrupt folder cache for subfolders of INBOX
  12. /**
  13. * do not allow to call this file directly
  14. */
  15. if (isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME'] == __FILE__) {
  16. header("Location: ../../src/login.php");
  17. die();
  18. }
  19. /** load globals */
  20. global $UseSeparateImapConnection,
  21. $AllowSpamFilters, $SpamFilters_YourHop, $SpamFilters_ShowCommercial,
  22. $SpamFilters_DNScache, $SpamFilters_BulkQuery, $SpamFilters_SharedCache,
  23. $SpamFilters_CacheTTL;
  24. /**
  25. * load required functions. Plugin depends on IMAP functions and they are not
  26. * loaded in src/webmail.php
  27. */
  28. include_once (SM_PATH . 'functions/imap.php');
  29. /** load default config */
  30. if (file_exists(SM_PATH . 'plugins/filters/config_default.php')) {
  31. include_once (SM_PATH . 'plugins/filters/config_default.php');
  32. } else {
  33. // default config was removed.
  34. $UseSeparateImapConnection = false;
  35. $AllowSpamFilters = true;
  36. $SpamFilters_YourHop = ' ';
  37. $SpamFilters_ShowCommercial = false;
  38. $SpamFilters_DNScache = array();
  39. $SpamFilters_BulkQuery = '';
  40. $SpamFilters_SharedCache = true;
  41. $SpamFilters_CacheTTL = 7200;
  42. }
  43. if (file_exists(SM_PATH . 'config/filters_config.php')) {
  44. include_once (SM_PATH . 'config/filters_config.php');
  45. } elseif (file_exists(SM_PATH . 'plugins/filters/config.php')) {
  46. include_once (SM_PATH . 'plugins/filters/config.php');
  47. }
  48. /**
  49. * Register option blocks
  50. * @access private
  51. */
  52. function filters_optpage_register_block() {
  53. global $optpage_blocks, $AllowSpamFilters;
  54. $optpage_blocks[] = array(
  55. 'name' => _("Message Filters"),
  56. 'url' => SM_PATH . 'plugins/filters/options.php',
  57. 'desc' => _("Filtering enables messages with different criteria to be automatically filtered into different folders for easier organization."),
  58. 'js' => false
  59. );
  60. if ($AllowSpamFilters) {
  61. $optpage_blocks[] = array(
  62. 'name' => _("SPAM Filters"),
  63. 'url' => SM_PATH . 'plugins/filters/spamoptions.php',
  64. 'desc' => _("SPAM filters allow you to select from various DNS based blacklists to detect junk email in your INBOX and move it to another folder (like Trash)."),
  65. 'js' => false
  66. );
  67. }
  68. }
  69. /* Receive the status of the folder and do something with it */
  70. function filters_folder_status($statusarr) {
  71. global $filter_inbox_count;
  72. if (empty($filter_inbox_count)) $filter_inbox_count=0;
  73. if ($statusarr['MAILBOX'] == 'INBOX')
  74. {
  75. if (!empty($statusarr['MESSAGES'])) $filter_inbox_count=$statusarr['MESSAGES'];
  76. }
  77. }
  78. /**
  79. * Saves the DNS Cache to disk
  80. * @access private
  81. */
  82. function filters_SaveCache () {
  83. global $data_dir, $SpamFilters_DNScache;
  84. if (file_exists($data_dir . '/dnscache')) {
  85. $fp = fopen($data_dir . '/dnscache', 'r');
  86. } else {
  87. $fp = false;
  88. }
  89. if ($fp) {
  90. flock($fp,LOCK_EX);
  91. } else {
  92. $fp = fopen($data_dir . '/dnscache', 'w+');
  93. fclose($fp);
  94. $fp = fopen($data_dir . '/dnscache', 'r');
  95. flock($fp,LOCK_EX);
  96. }
  97. $fp1 = fopen($data_dir . '/dnscache', 'w+');
  98. foreach ($SpamFilters_DNScache as $Key=> $Value) {
  99. $tstr = $Key . ',' . $Value['L'] . ',' . $Value['T'] . "\n";
  100. fputs ($fp1, $tstr);
  101. }
  102. fclose($fp1);
  103. flock($fp,LOCK_UN);
  104. fclose($fp);
  105. }
  106. /**
  107. * Loads the DNS Cache from disk
  108. * @access private
  109. */
  110. function filters_LoadCache () {
  111. global $data_dir, $SpamFilters_DNScache;
  112. if (file_exists($data_dir . '/dnscache')) {
  113. $SpamFilters_DNScache = array();
  114. if ($fp = fopen ($data_dir . '/dnscache', 'r')) {
  115. flock($fp,LOCK_SH);
  116. while ($data = fgetcsv($fp,1024,',','"','')) {
  117. if ($data[2] > time()) {
  118. $SpamFilters_DNScache[$data[0]]['L'] = $data[1];
  119. $SpamFilters_DNScache[$data[0]]['T'] = $data[2];
  120. }
  121. }
  122. flock($fp,LOCK_UN);
  123. }
  124. }
  125. }
  126. /**
  127. * Uses the BulkQuery executable to query all the RBLs at once
  128. * @param array $filters Array of SPAM Filters
  129. * @param array $IPs Array of IP Addresses
  130. * @access private
  131. */
  132. function filters_bulkquery($filters, $IPs) {
  133. global $attachment_dir, $username,
  134. $SpamFilters_DNScache, $SpamFilters_BulkQuery,
  135. $SpamFilters_CacheTTL;
  136. if (count($IPs) > 0) {
  137. $rbls = array();
  138. foreach ($filters as $key => $value) {
  139. if ($filters[$key]['enabled']) {
  140. if ($filters[$key]['dns']) {
  141. $rbls[$filters[$key]['dns']] = true;
  142. }
  143. }
  144. }
  145. $bqfil = $attachment_dir . $username . '-bq.in';
  146. $fp = fopen($bqfil, 'w');
  147. fputs ($fp, $SpamFilters_CacheTTL . "\n");
  148. foreach ($rbls as $key => $value) {
  149. fputs ($fp, '.' . $key . "\n");
  150. }
  151. fputs ($fp, "----------\n");
  152. foreach ($IPs as $key => $value) {
  153. fputs ($fp, $key . "\n");
  154. }
  155. fclose ($fp);
  156. $bqout = array();
  157. exec ($SpamFilters_BulkQuery . ' < ' . $bqfil, $bqout);
  158. foreach ($bqout as $value) {
  159. $Chunks = explode(',', $value);
  160. $SpamFilters_DNScache[$Chunks[0]]['L'] = $Chunks[1];
  161. $SpamFilters_DNScache[$Chunks[0]]['T'] = $Chunks[2] + time();
  162. }
  163. unlink($bqfil);
  164. }
  165. }
  166. /**
  167. * Starts the filtering process
  168. * @param array $hook_args (since 1.5.2) do hook arguments. Is used to check
  169. * hook name, array key = 0.
  170. * @access private
  171. */
  172. function start_filters($hook_args) {
  173. global $imapServerAddress, $imapPort, $imap_stream_options, $imap_stream,
  174. $imapConnection, $UseSeparateImapConnection, $AllowSpamFilters,
  175. $filter_inbox_count, $username;
  176. // if there were filtering errors previously during
  177. // this login session, we won't try again
  178. //
  179. // (errors that this plugin was able to catch or a "NO"
  180. // response/failure from IMAP found in the current session,
  181. // which could have resulted from an attempted filter copy
  182. // (over quota), in which case execution halts before this
  183. // plugin can catch the problem -- note, however, that any
  184. // other IMAP "NO" failure (caused by unrelated actions) at
  185. // any time during the current session will cause this plugin
  186. // to effectively shut down)
  187. //
  188. sqgetGlobalVar('filters_error', $filters_error, SQ_SESSION, FALSE);
  189. sqgetGlobalVar('IMAP_FATAL_ERROR_TYPE', $imap_fatal_error, SQ_SESSION, '');
  190. if ($filters_error || $imap_fatal_error == 'NO')
  191. return;
  192. /**
  193. * check hook that calls filtering. If filters are called by right_main_after_header,
  194. * do filtering only when we are in INBOX folder.
  195. */
  196. if ($hook_args !== null && $hook_args[0]=='right_main_after_header' &&
  197. (sqgetGlobalVar('mailbox',$mailbox,SQ_FORM) && $mailbox!='INBOX')) {
  198. return;
  199. }
  200. $filters = load_filters();
  201. // No point running spam filters if there aren't any to run //
  202. if ($AllowSpamFilters) {
  203. $spamfilters = load_spam_filters();
  204. $AllowSpamFilters = false;
  205. foreach($spamfilters as $value) {
  206. if ($value['enabled'] == SMPREF_ON) {
  207. $AllowSpamFilters = true;
  208. break;
  209. }
  210. }
  211. }
  212. // No user filters, and no spam filters, no need to continue //
  213. if (!$AllowSpamFilters && empty($filters)) {
  214. return;
  215. }
  216. // Detect if we have already connected to IMAP or not.
  217. // Also check if we are forced to use a separate IMAP connection
  218. if ((!isset($imap_stream) && !isset($imapConnection)) ||
  219. $UseSeparateImapConnection ) {
  220. $stream = sqimap_login($username, false, $imapServerAddress,
  221. $imapPort, 10, $imap_stream_options);
  222. $previously_connected = false;
  223. } else if (isset($imapConnection)) {
  224. $stream = $imapConnection;
  225. $previously_connected = true;
  226. } else {
  227. $previously_connected = true;
  228. $stream = $imap_stream;
  229. }
  230. if (!isset($filter_inbox_count)) {
  231. $aStatus = sqimap_status_messages ($stream, 'INBOX', array('MESSAGES'));
  232. if (!empty($aStatus['MESSAGES'])) {
  233. $filter_inbox_count=$aStatus['MESSAGES'];
  234. } else {
  235. $filter_inbox_count=0;
  236. }
  237. }
  238. if ($filter_inbox_count > 0) {
  239. sqimap_mailbox_select($stream, 'INBOX');
  240. // Filter spam from inbox before we sort them into folders
  241. if ($AllowSpamFilters) {
  242. spam_filters($stream);
  243. }
  244. // Sort into folders
  245. user_filters($stream);
  246. }
  247. if (!$previously_connected) {
  248. sqimap_logout($stream);
  249. }
  250. }
  251. /**
  252. * Does the loop through each filter
  253. * @param stream imap_stream the stream to read from
  254. * @access private
  255. */
  256. function user_filters($imap_stream) {
  257. global $data_dir, $username;
  258. $filters = load_filters();
  259. if (! $filters) return;
  260. $filters_user_scan = getPref($data_dir, $username, 'filters_user_scan');
  261. $expunge = false;
  262. // For every rule
  263. for ($i=0, $num = count($filters); $i < $num; $i++) {
  264. // If it is the "combo" rule
  265. if ($filters[$i]['where'] == 'To or Cc') {
  266. /*
  267. * If it's "TO OR CC", we have to do two searches, one for TO
  268. * and the other for CC.
  269. */
  270. $expunge = filter_search_and_delete($imap_stream, 'TO',
  271. $filters[$i]['what'], $filters[$i]['folder'], $filters_user_scan, $expunge);
  272. $expunge = filter_search_and_delete($imap_stream, 'CC',
  273. $filters[$i]['what'], $filters[$i]['folder'], $filters_user_scan, $expunge);
  274. } else if ($filters[$i]['where'] == 'Header and Body') {
  275. $expunge = filter_search_and_delete($imap_stream, 'TEXT',
  276. $filters[$i]['what'], $filters[$i]['folder'], $filters_user_scan, $expunge);
  277. } else if ($filters[$i]['where'] == 'Message Body') {
  278. $expunge = filter_search_and_delete($imap_stream, 'BODY',
  279. $filters[$i]['what'], $filters[$i]['folder'], $filters_user_scan, $expunge);
  280. } else {
  281. /*
  282. * If it's a normal TO, CC, SUBJECT, or FROM, then handle it
  283. * normally.
  284. */
  285. $expunge = filter_search_and_delete($imap_stream, $filters[$i]['where'],
  286. $filters[$i]['what'], $filters[$i]['folder'], $filters_user_scan, $expunge);
  287. }
  288. }
  289. // Clean out the mailbox whether or not auto_expunge is on
  290. // That way it looks like it was redirected properly
  291. if ($expunge) {
  292. sqimap_mailbox_expunge($imap_stream, 'INBOX');
  293. }
  294. }
  295. /**
  296. * Creates and runs the IMAP command to filter messages
  297. * @param string $imap_stream TODO: Document this parameter
  298. * @param string $where Which part of the message to search (TO, CC, SUBJECT, etc...)
  299. * @param string $what String to search for
  300. * @param string $where_to Folder it will move to
  301. * @param string $user_scan Whether to search all or just unseen
  302. * @param string $should_expunge
  303. * @access private
  304. */
  305. function filter_search_and_delete($imap_stream, $where, $what, $where_to, $user_scan,
  306. $should_expunge) {
  307. global $languages, $squirrelmail_language, $allow_charset_search, $imap_server_type;
  308. //TODO: make use of new mailbox cache. See mailbox_display.phpinfo
  309. if (strtolower($where_to) == 'inbox') {
  310. return array();
  311. }
  312. if ($user_scan == 'new') {
  313. $category = 'UNSEEN';
  314. } else {
  315. $category = 'ALL';
  316. }
  317. $category .= ' UNDELETED';
  318. if ($allow_charset_search &&
  319. isset($languages[$squirrelmail_language]['CHARSET']) &&
  320. $languages[$squirrelmail_language]['CHARSET']) {
  321. $search_str = 'SEARCH CHARSET '
  322. . strtoupper($languages[$squirrelmail_language]['CHARSET'])
  323. . ' ' . $category;
  324. } else {
  325. $search_str = 'SEARCH CHARSET US-ASCII ' . $category;
  326. }
  327. if ($where == 'Header') {
  328. $what = explode(':', $what);
  329. $where = strtoupper($where);
  330. $where = trim($where . ' ' . $what[0]);
  331. $what = addslashes(trim($what[1]));
  332. }
  333. // see comments in squirrelmail sqimap_search function
  334. if ($imap_server_type == 'macosx' || $imap_server_type == 'hmailserver') {
  335. $search_str .= ' ' . $where . ' ' . $what;
  336. /* read data back from IMAP */
  337. $read = sqimap_run_command($imap_stream, $search_str, true, $response, $message, TRUE);
  338. } else {
  339. $search_str .= ' ' . $where . ' {' . strlen($what) . "}";
  340. $sid = sqimap_session_id(true);
  341. fputs ($imap_stream, $sid . ' ' . $search_str . "\r\n");
  342. $read2 = sqimap_fgets($imap_stream);
  343. # server should respond with Ready for argument, then we will send search text
  344. #echo "RR2 $read2<br>";
  345. fputs ($imap_stream, "$what\r\n");
  346. #echo "SS $what<br>";
  347. $read2 = sqimap_fgets($imap_stream);
  348. #echo "RR2 $read2<br>";
  349. $read[]=$read2;
  350. $read3 = sqimap_fgets($imap_stream);
  351. #echo "RR3 $read3<br>";
  352. list($rtag,$response,$message)=explode(' ',$read3,3);
  353. ## $read2 = sqimap_retrieve_imap_response($imap_stream, $sid, true,
  354. ## $response, $message, $search_str, false, true, false);
  355. #echo "RR2 $read2 / RESPONSE $response<br>";
  356. }
  357. if (isset($read[0])) {
  358. $ids = array();
  359. for ($i = 0, $iCnt = count($read); $i < $iCnt; ++$i) {
  360. if (preg_match("/^\* SEARCH (.+)$/", $read[$i], $regs)) {
  361. $ids += explode(' ', trim($regs[1]));
  362. }
  363. }
  364. if ($response == 'OK' && count($ids)) {
  365. if (sqimap_mailbox_exists($imap_stream, $where_to)) {
  366. if (!sqimap_msgs_list_move ($imap_stream, $ids, $where_to, false)) {
  367. // if errors occurred, don't try to filter again during this session
  368. sqsession_register(TRUE, 'filters_error');
  369. global $color;
  370. error_box(_("A problem occurred filtering messages. Check filter settings and account quota if applicable. Filtering is disabled for the remainder of this login session."), $color);
  371. }
  372. // expunge even in the case of errors, in case some
  373. // messages were filtered before the error happened
  374. $should_expunge = true;
  375. }
  376. } elseif ($response != 'OK') {
  377. $query = $search_str . "\r\n".$what ."\r\n";
  378. if ($response == 'NO') {
  379. if (strpos($message,'BADCHARSET') !== false ||
  380. strpos($message,'character') !== false) {
  381. sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
  382. } else {
  383. sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
  384. }
  385. } else {
  386. sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
  387. }
  388. }
  389. }
  390. return $should_expunge;
  391. }
  392. /**
  393. * Loops through all the Received Headers to find IP Addresses
  394. * @param stream imap_stream the stream to read from
  395. * @access private
  396. */
  397. function spam_filters($imap_stream) {
  398. global $data_dir, $username;
  399. global $SpamFilters_YourHop;
  400. global $SpamFilters_DNScache;
  401. global $SpamFilters_SharedCache;
  402. global $SpamFilters_BulkQuery;
  403. global $SpamFilters_CacheTTL;
  404. $filters_spam_scan = getPref($data_dir, $username, 'filters_spam_scan');
  405. $filters_spam_folder = getPref($data_dir, $username, 'filters_spam_folder');
  406. $filters = load_spam_filters();
  407. if ($SpamFilters_SharedCache) {
  408. filters_LoadCache();
  409. }
  410. $run = false;
  411. foreach ($filters as $Value) {
  412. if ($Value['enabled']) {
  413. $run = true;
  414. break;
  415. }
  416. }
  417. // short-circuit
  418. if (!$run) {
  419. return;
  420. }
  421. // Ask for a big list of all "Received" headers in the inbox with
  422. // flags for each message. Kinda big.
  423. if ($filters_spam_scan == 'new') {
  424. $search_array = array();
  425. $read = sqimap_run_command($imap_stream, 'SEARCH UNSEEN', true, $response, $message, TRUE);
  426. if (isset($read[0])) {
  427. for ($i = 0, $iCnt = count($read); $i < $iCnt; ++$i) {
  428. if (preg_match("/^\* SEARCH (.+)$/", $read[$i], $regs)) {
  429. $search_array = explode(' ', trim($regs[1]));
  430. break;
  431. }
  432. }
  433. }
  434. }
  435. if ($filters_spam_scan == 'new' && count($search_array)) {
  436. $headers = sqimap_get_small_header_list ($imap_stream, $search_array, array('Received'),array());
  437. } else if ($filters_spam_scan != 'new') {
  438. $headers = sqimap_get_small_header_list ($imap_stream, null , array('Received'),array());
  439. } else {
  440. return;
  441. }
  442. if (!count($headers)) {
  443. return;
  444. }
  445. $bulkquery = (strlen($SpamFilters_BulkQuery) > 0 ? true : false);
  446. $IPs = array();
  447. $aSpamIds = array();
  448. foreach ($headers as $id => $aValue) {
  449. if (isset($aValue['UID'])) {
  450. $MsgNum = $aValue['UID'];
  451. } else {
  452. $MsgNum = $id;
  453. }
  454. // Look through all of the Received headers for IP addresses
  455. if (isset($aValue['RECEIVED'])) {
  456. foreach ($aValue['RECEIVED'] as $received) {
  457. // Check to see if this line is the right "Received from" line
  458. // to check
  459. // $aValue['Received'] is an array with all the received lines.
  460. // We should check them from bottom to top and only check the first 2.
  461. // Currently we check only the header where $SpamFilters_YourHop in occures
  462. if (is_int(strpos($received, $SpamFilters_YourHop))) {
  463. if (preg_match('/([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/',$received,$aMatch)) {
  464. $isspam = false;
  465. if (filters_spam_check_site($aMatch[1],$aMatch[2],$aMatch[3],$aMatch[4],$filters)) {
  466. $aSpamIds[] = $MsgNum;
  467. $isspam = true;
  468. }
  469. if ($bulkquery) {
  470. array_shift($aMatch);
  471. $IP = explode('.', $aMatch);
  472. foreach ($filters as $key => $value) {
  473. if ($filters[$key]['enabled'] && $filters[$key]['dns']) {
  474. if (strlen($SpamFilters_DNScache[$IP.'.'.$filters[$key]['dns']]) == 0) {
  475. $IPs[$IP] = true;
  476. break;
  477. }
  478. }
  479. }
  480. }
  481. // If we've checked one IP and YourHop is
  482. // just a space
  483. if ($SpamFilters_YourHop == ' ' || $isspam) {
  484. break; // don't check any more
  485. }
  486. }
  487. }
  488. }
  489. }
  490. }
  491. // Lookie! It's spam! Yum!
  492. if (count($aSpamIds) && sqimap_mailbox_exists($imap_stream, $filters_spam_folder)) {
  493. if (!sqimap_msgs_list_move($imap_stream, $aSpamIds, $filters_spam_folder)) {
  494. // if errors occurred, don't try to filter again during this session
  495. sqsession_register(TRUE, 'filters_error');
  496. global $color;
  497. error_box(_("A problem occurred filtering messages. Check filter settings and account quota if applicable. Filtering is disabled for the remainder of this login session."), $color);
  498. }
  499. // expunge even in the case of errors, in case some
  500. // messages were filtered before the error happened
  501. sqimap_mailbox_expunge($imap_stream, 'INBOX');
  502. }
  503. if ($bulkquery && count($IPs)) {
  504. filters_bulkquery($filters, $IPs);
  505. }
  506. if ($SpamFilters_SharedCache) {
  507. filters_SaveCache();
  508. } else {
  509. sqsession_register($SpamFilters_DNScache, 'SpamFilters_DNScache');
  510. }
  511. }
  512. /**
  513. * Does the loop through each enabled filter for the specified IP address.
  514. * IP format: $a.$b.$c.$d
  515. * @param int $a First subset of IP
  516. * @param int $b Second subset of IP
  517. * @param int $c Third subset of IP
  518. * @param int $d Forth subset of IP
  519. * @param array $filters The Spam Filters
  520. * @return boolean Whether the IP is Spam
  521. * @access private
  522. */
  523. function filters_spam_check_site($a, $b, $c, $d, &$filters) {
  524. global $SpamFilters_DNScache, $SpamFilters_CacheTTL;
  525. foreach ($filters as $key => $value) {
  526. if ($filters[$key]['enabled']) {
  527. if ($filters[$key]['dns']) {
  528. /**
  529. * RFC allows . on end of hostname to force domain lookup to
  530. * not use search domain from resolv.conf, i.e. to ensure
  531. * search domain isn't used if no hostname is found
  532. */
  533. $filter_revip = $d . '.' . $c . '.' . $b . '.' . $a . '.' .
  534. $filters[$key]['dns'] . '.';
  535. if(!isset($SpamFilters_DNScache[$filter_revip]['L']))
  536. $SpamFilters_DNScache[$filter_revip]['L'] = '';
  537. if(!isset($SpamFilters_DNScache[$filter_revip]['T']))
  538. $SpamFilters_DNScache[$filter_revip]['T'] = '';
  539. if (strlen($SpamFilters_DNScache[$filter_revip]['L']) == 0) {
  540. $SpamFilters_DNScache[$filter_revip]['L'] =
  541. gethostbyname($filter_revip);
  542. $SpamFilters_DNScache[$filter_revip]['T'] =
  543. time() + $SpamFilters_CacheTTL;
  544. }
  545. /**
  546. * gethostbyname returns ip if resolved, or returns original
  547. * host supplied to function if there is no resolution
  548. */
  549. if ($SpamFilters_DNScache[$filter_revip]['L'] != $filter_revip) {
  550. return 1;
  551. }
  552. }
  553. }
  554. }
  555. return 0;
  556. }
  557. /**
  558. * Loads the filters from the user preferences
  559. * @return array All the user filters
  560. * @access private
  561. */
  562. function load_filters() {
  563. global $data_dir, $username;
  564. $filters = array();
  565. for ($i = 0; $fltr = getPref($data_dir, $username, 'filter' . $i); $i++) {
  566. $ary = explode(',', $fltr);
  567. $filters[$i]['where'] = $ary[0];
  568. $filters[$i]['what'] = str_replace('###COMMA###', ',', $ary[1]);
  569. $filters[$i]['folder'] = $ary[2];
  570. }
  571. return $filters;
  572. }
  573. /**
  574. * Loads the Spam Filters and checks the preferences for the enabled status
  575. * @return array All the spam filters
  576. * @access private
  577. */
  578. function load_spam_filters() {
  579. global $data_dir, $username, $SpamFilters_ShowCommercial;
  580. if ($SpamFilters_ShowCommercial) {
  581. $filters['MAPS RBL']['prefname'] = 'filters_spam_maps_rbl';
  582. $filters['MAPS RBL']['name'] = 'MAPS Realtime Blackhole List';
  583. $filters['MAPS RBL']['link'] = 'http://www.mail-abuse.org/rbl/';
  584. $filters['MAPS RBL']['dns'] = 'blackholes.mail-abuse.org';
  585. $filters['MAPS RBL']['result'] = '127.0.0.2';
  586. $filters['MAPS RBL']['comment'] =
  587. _("COMMERCIAL - This list contains servers that are verified spam senders. It is a pretty reliable list to scan spam from.");
  588. $filters['MAPS RSS']['prefname'] = 'filters_spam_maps_rss';
  589. $filters['MAPS RSS']['name'] = 'MAPS Relay Spam Stopper';
  590. $filters['MAPS RSS']['link'] = 'http://www.mail-abuse.org/rss/';
  591. $filters['MAPS RSS']['dns'] = 'relays.mail-abuse.org';
  592. $filters['MAPS RSS']['result'] = '127.0.0.2';
  593. $filters['MAPS RSS']['comment'] =
  594. _("COMMERCIAL - Servers that are configured (or misconfigured) to allow spam to be relayed through their system will be banned with this. Another good one to use.");
  595. $filters['MAPS DUL']['prefname'] = 'filters_spam_maps_dul';
  596. $filters['MAPS DUL']['name'] = 'MAPS Dial-Up List';
  597. $filters['MAPS DUL']['link'] = 'http://www.mail-abuse.org/dul/';
  598. $filters['MAPS DUL']['dns'] = 'dialups.mail-abuse.org';
  599. $filters['MAPS DUL']['result'] = '127.0.0.3';
  600. $filters['MAPS DUL']['comment'] =
  601. _("COMMERCIAL - Dial-up users are often filtered out since they should use their ISP's mail servers to send mail. Spammers typically get a dial-up account and send spam directly from there.");
  602. $filters['MAPS RBLplus-RBL']['prefname'] = 'filters_spam_maps_rblplus_rbl';
  603. $filters['MAPS RBLplus-RBL']['name'] = 'MAPS RBL+ RBL List';
  604. $filters['MAPS RBLplus-RBL']['link'] = 'http://www.mail-abuse.org/';
  605. $filters['MAPS RBLplus-RBL']['dns'] = 'rbl-plus.mail-abuse.org';
  606. $filters['MAPS RBLplus-RBL']['result'] = '127.0.0.2';
  607. $filters['MAPS RBLplus-RBL']['comment'] =
  608. _("COMMERCIAL - RBL+ Blackhole entries.");
  609. $filters['MAPS RBLplus-RSS']['prefname'] = 'filters_spam_maps_rblplus_rss';
  610. $filters['MAPS RBLplus-RSS']['name'] = 'MAPS RBL+ List RSS entries';
  611. $filters['MAPS RBLplus-RSS']['link'] = 'http://www.mail-abuse.org/';
  612. $filters['MAPS RBLplus-RSS']['dns'] = 'rbl-plus.mail-abuse.org';
  613. $filters['MAPS RBLplus-RSS']['result'] = '127.0.0.2';
  614. $filters['MAPS RBLplus-RSS']['comment'] =
  615. _("COMMERCIAL - RBL+ OpenRelay entries.");
  616. $filters['MAPS RBLplus-DUL']['prefname'] = 'filters_spam_maps_rblplus_dul';
  617. $filters['MAPS RBLplus-DUL']['name'] = 'MAPS RBL+ List DUL entries';
  618. $filters['MAPS RBLplus-DUL']['link'] = 'http://www.mail-abuse.org/';
  619. $filters['MAPS RBLplus-DUL']['dns'] = 'rbl-plus.mail-abuse.org';
  620. $filters['MAPS RBLplus-DUL']['result'] = '127.0.0.3';
  621. $filters['MAPS RBLplus-DUL']['comment'] =
  622. _("COMMERCIAL - RBL+ Dial-up entries.");
  623. }
  624. $filters['FiveTen Direct']['prefname'] = 'filters_spam_fiveten_src';
  625. $filters['FiveTen Direct']['name'] = 'Five-Ten-sg.com Direct SPAM Sources';
  626. $filters['FiveTen Direct']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  627. $filters['FiveTen Direct']['dns'] = 'blackholes.five-ten-sg.com';
  628. $filters['FiveTen Direct']['result'] = '127.0.0.2';
  629. $filters['FiveTen Direct']['comment'] =
  630. _("FREE - Five-Ten-sg.com - Direct SPAM sources.");
  631. $filters['FiveTen DUL']['prefname'] = 'filters_spam_fiveten_dul';
  632. $filters['FiveTen DUL']['name'] = 'Five-Ten-sg.com DUL Lists';
  633. $filters['FiveTen DUL']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  634. $filters['FiveTen DUL']['dns'] = 'blackholes.five-ten-sg.com';
  635. $filters['FiveTen DUL']['result'] = '127.0.0.3';
  636. $filters['FiveTen DUL']['comment'] =
  637. _("FREE - Five-Ten-sg.com - Dial-up lists - includes some DSL IPs.");
  638. $filters['FiveTen Unc. OptIn']['prefname'] = 'filters_spam_fiveten_oi';
  639. $filters['FiveTen Unc. OptIn']['name'] = 'Five-Ten-sg.com Unconfirmed OptIn Lists';
  640. $filters['FiveTen Unc. OptIn']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  641. $filters['FiveTen Unc. OptIn']['dns'] = 'blackholes.five-ten-sg.com';
  642. $filters['FiveTen Unc. OptIn']['result'] = '127.0.0.4';
  643. $filters['FiveTen Unc. OptIn']['comment'] =
  644. _("FREE - Five-Ten-sg.com - Bulk mailers that do not use confirmed opt-in.");
  645. $filters['FiveTen Others']['prefname'] = 'filters_spam_fiveten_oth';
  646. $filters['FiveTen Others']['name'] = 'Five-Ten-sg.com Other Misc. Servers';
  647. $filters['FiveTen Others']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  648. $filters['FiveTen Others']['dns'] = 'blackholes.five-ten-sg.com';
  649. $filters['FiveTen Others']['result'] = '127.0.0.5';
  650. $filters['FiveTen Others']['comment'] =
  651. _("FREE - Five-Ten-sg.com - Other misc. servers.");
  652. $filters['FiveTen Single Stage']['prefname'] = 'filters_spam_fiveten_ss';
  653. $filters['FiveTen Single Stage']['name'] = 'Five-Ten-sg.com Single Stage Servers';
  654. $filters['FiveTen Single Stage']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  655. $filters['FiveTen Single Stage']['dns'] = 'blackholes.five-ten-sg.com';
  656. $filters['FiveTen Single Stage']['result'] = '127.0.0.6';
  657. $filters['FiveTen Single Stage']['comment'] =
  658. _("FREE - Five-Ten-sg.com - Single Stage servers.");
  659. $filters['FiveTen SPAM Support']['prefname'] = 'filters_spam_fiveten_supp';
  660. $filters['FiveTen SPAM Support']['name'] = 'Five-Ten-sg.com SPAM Support Servers';
  661. $filters['FiveTen SPAM Support']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  662. $filters['FiveTen SPAM Support']['dns'] = 'blackholes.five-ten-sg.com';
  663. $filters['FiveTen SPAM Support']['result'] = '127.0.0.7';
  664. $filters['FiveTen SPAM Support']['comment'] =
  665. _("FREE - Five-Ten-sg.com - SPAM Support servers.");
  666. $filters['FiveTen Web forms']['prefname'] = 'filters_spam_fiveten_wf';
  667. $filters['FiveTen Web forms']['name'] = 'Five-Ten-sg.com Web Form IPs';
  668. $filters['FiveTen Web forms']['link'] = 'http://www.five-ten-sg.com/blackhole.php';
  669. $filters['FiveTen Web forms']['dns'] = 'blackholes.five-ten-sg.com';
  670. $filters['FiveTen Web forms']['result'] = '127.0.0.8';
  671. $filters['FiveTen Web forms']['comment'] =
  672. _("FREE - Five-Ten-sg.com - Web Form IPs.");
  673. $filters['Dorkslayers']['prefname'] = 'filters_spam_dorks';
  674. $filters['Dorkslayers']['name'] = 'Dorkslayers Lists';
  675. $filters['Dorkslayers']['link'] = 'http://www.dorkslayers.com';
  676. $filters['Dorkslayers']['dns'] = 'orbs.dorkslayers.com';
  677. $filters['Dorkslayers']['result'] = '127.0.0.2';
  678. $filters['Dorkslayers']['comment'] =
  679. _("FREE - Dorkslayers appears to include only really bad open relays outside the US to avoid being sued. Interestingly enough, their website recommends you NOT use their service.");
  680. $filters['SPAMhaus']['prefname'] = 'filters_spam_spamhaus';
  681. $filters['SPAMhaus']['name'] = 'SPAMhaus Lists';
  682. $filters['SPAMhaus']['link'] = 'http://www.spamhaus.org';
  683. $filters['SPAMhaus']['dns'] = 'sbl.spamhaus.org';
  684. $filters['SPAMhaus']['result'] = '127.0.0.2';
  685. $filters['SPAMhaus']['comment'] =
  686. _("FREE - SPAMhaus - A list of well-known SPAM sources.");
  687. $filters['SPAMcop']['prefname'] = 'filters_spam_spamcop';
  688. $filters['SPAMcop']['name'] = 'SPAM Cop Lists';
  689. $filters['SPAMcop']['link'] = 'http://spamcop.net/bl.shtml';
  690. $filters['SPAMcop']['dns'] = 'bl.spamcop.net';
  691. $filters['SPAMcop']['result'] = '127.0.0.2';
  692. $filters['SPAMcop']['comment'] =
  693. _("FREE, for now - SpamCop - An interesting solution that lists servers that have a very high spam to legit email ratio (85 percent or more).");
  694. $filters['dev.null.dk']['prefname'] = 'filters_spam_devnull';
  695. $filters['dev.null.dk']['name'] = 'dev.null.dk Lists';
  696. $filters['dev.null.dk']['link'] = 'http://dev.null.dk/';
  697. $filters['dev.null.dk']['dns'] = 'dev.null.dk';
  698. $filters['dev.null.dk']['result'] = '127.0.0.2';
  699. $filters['dev.null.dk']['comment'] =
  700. _("FREE - dev.null.dk - I don't have any detailed info on this list.");
  701. $filters['visi.com']['prefname'] = 'filters_spam_visi';
  702. $filters['visi.com']['name'] = 'visi.com Relay Stop List';
  703. $filters['visi.com']['link'] = 'http://relays.visi.com';
  704. $filters['visi.com']['dns'] = 'relays.visi.com';
  705. $filters['visi.com']['result'] = '127.0.0.2';
  706. $filters['visi.com']['comment'] =
  707. _("FREE - visi.com - Relay Stop List. Very conservative OpenRelay List.");
  708. $filters['ahbl.org Open Relays']['prefname'] = 'filters_spam_2mb_or';
  709. $filters['ahbl.org Open Relays']['name'] = 'ahbl.org Open Relays List';
  710. $filters['ahbl.org Open Relays']['link'] = 'http://www.ahbl.org/';
  711. $filters['ahbl.org Open Relays']['dns'] = 'dnsbl.ahbl.org';
  712. $filters['ahbl.org Open Relays']['result'] = '127.0.0.2';
  713. $filters['ahbl.org Open Relays']['comment'] =
  714. _("FREE - ahbl.org Open Relays - Another list of Open Relays.");
  715. $filters['ahbl.org SPAM Source']['prefname'] = 'filters_spam_2mb_ss';
  716. $filters['ahbl.org SPAM Source']['name'] = 'ahbl.org SPAM Source List';
  717. $filters['ahbl.org SPAM Source']['link'] = 'http://www.ahbl.org/';
  718. $filters['ahbl.org SPAM Source']['dns'] = 'dnsbl.ahbl.org';
  719. $filters['ahbl.org SPAM Source']['result'] = '127.0.0.4';
  720. $filters['ahbl.org SPAM Source']['comment'] =
  721. _("FREE - ahbl.org SPAM Source - List of Direct SPAM Sources.");
  722. $filters['ahbl.org SPAM ISPs']['prefname'] = 'filters_spam_2mb_isp';
  723. $filters['ahbl.org SPAM ISPs']['name'] = 'ahbl.org SPAM-friendly ISP List';
  724. $filters['ahbl.org SPAM ISPs']['link'] = 'http://www.ahbl.org/';
  725. $filters['ahbl.org SPAM ISPs']['dns'] = 'dnsbl.ahbl.org';
  726. $filters['ahbl.org SPAM ISPs']['result'] = '127.0.0.7';
  727. $filters['ahbl.org SPAM ISPs']['comment'] =
  728. _("FREE - ahbl.org SPAM ISPs - List of SPAM-friendly ISPs.");
  729. $filters['Leadmon DUL']['prefname'] = 'filters_spam_lm_dul';
  730. $filters['Leadmon DUL']['name'] = 'Leadmon.net DUL List';
  731. $filters['Leadmon DUL']['link'] = 'http://www.leadmon.net/spamguard/';
  732. $filters['Leadmon DUL']['dns'] = 'spamguard.leadmon.net';
  733. $filters['Leadmon DUL']['result'] = '127.0.0.2';
  734. $filters['Leadmon DUL']['comment'] =
  735. _("FREE - Leadmon DUL - Another list of Dial-up or otherwise dynamically assigned IPs.");
  736. $filters['Leadmon SPAM Source']['prefname'] = 'filters_spam_lm_ss';
  737. $filters['Leadmon SPAM Source']['name'] = 'Leadmon.net SPAM Source List';
  738. $filters['Leadmon SPAM Source']['link'] = 'http://www.leadmon.net/spamguard/';
  739. $filters['Leadmon SPAM Source']['dns'] = 'spamguard.leadmon.net';
  740. $filters['Leadmon SPAM Source']['result'] = '127.0.0.3';
  741. $filters['Leadmon SPAM Source']['comment'] =
  742. _("FREE - Leadmon SPAM Source - List of IPs Leadmon.net has received SPAM directly from.");
  743. $filters['Leadmon Bulk Mailers']['prefname'] = 'filters_spam_lm_bm';
  744. $filters['Leadmon Bulk Mailers']['name'] = 'Leadmon.net Bulk Mailers List';
  745. $filters['Leadmon Bulk Mailers']['link'] = 'http://www.leadmon.net/spamguard/';
  746. $filters['Leadmon Bulk Mailers']['dns'] = 'spamguard.leadmon.net';
  747. $filters['Leadmon Bulk Mailers']['result'] = '127.0.0.4';
  748. $filters['Leadmon Bulk Mailers']['comment'] =
  749. _("FREE - Leadmon Bulk Mailers - Bulk mailers that do not require confirmed opt-in or that have allowed known spammers to become clients and abuse their services.");
  750. $filters['Leadmon Open Relays']['prefname'] = 'filters_spam_lm_or';
  751. $filters['Leadmon Open Relays']['name'] = 'Leadmon.net Open Relays List';
  752. $filters['Leadmon Open Relays']['link'] = 'http://www.leadmon.net/spamguard/';
  753. $filters['Leadmon Open Relays']['dns'] = 'spamguard.leadmon.net';
  754. $filters['Leadmon Open Relays']['result'] = '127.0.0.5';
  755. $filters['Leadmon Open Relays']['comment'] =
  756. _("FREE - Leadmon Open Relays - Single Stage Open Relays that are not listed on other active RBLs.");
  757. $filters['Leadmon Multi-stage']['prefname'] = 'filters_spam_lm_ms';
  758. $filters['Leadmon Multi-stage']['name'] = 'Leadmon.net Multi-Stage Relay List';
  759. $filters['Leadmon Multi-stage']['link'] = 'http://www.leadmon.net/spamguard/';
  760. $filters['Leadmon Multi-stage']['dns'] = 'spamguard.leadmon.net';
  761. $filters['Leadmon Multi-stage']['result'] = '127.0.0.6';
  762. $filters['Leadmon Multi-stage']['comment'] =
  763. _("FREE - Leadmon Multi-stage - Multi-Stage Open Relays that are not listed on other active RBLs and that have sent SPAM to Leadmon.net.");
  764. $filters['Leadmon SpamBlock']['prefname'] = 'filters_spam_lm_sb';
  765. $filters['Leadmon SpamBlock']['name'] = 'Leadmon.net SpamBlock Sites List';
  766. $filters['Leadmon SpamBlock']['link'] = 'http://www.leadmon.net/spamguard/';
  767. $filters['Leadmon SpamBlock']['dns'] = 'spamguard.leadmon.net';
  768. $filters['Leadmon SpamBlock']['result'] = '127.0.0.7';
  769. $filters['Leadmon SpamBlock']['comment'] =
  770. _("FREE - Leadmon SpamBlock - Sites on this listing have sent Leadmon.net direct SPAM from IPs in netblocks where the entire block has no DNS mappings. It's a list of BLOCKS of IPs being used by people who have SPAMmed Leadmon.net.");
  771. $filters['NJABL Open Relays']['prefname'] = 'filters_spam_njabl_or';
  772. $filters['NJABL Open Relays']['name'] = 'NJABL Open Relay/Direct Spam Source List';
  773. $filters['NJABL Open Relays']['link'] = 'http://www.njabl.org/';
  774. $filters['NJABL Open Relays']['dns'] = 'dnsbl.njabl.org';
  775. $filters['NJABL Open Relays']['result'] = '127.0.0.2';
  776. $filters['NJABL Open Relays']['comment'] =
  777. _("FREE, for now - Not Just Another Blacklist - Both Open Relays and Direct SPAM Sources.");
  778. $filters['NJABL DUL']['prefname'] = 'filters_spam_njabl_dul';
  779. $filters['NJABL DUL']['name'] = 'NJABL Dial-ups List';
  780. $filters['NJABL DUL']['link'] = 'http://www.njabl.org/';
  781. $filters['NJABL DUL']['dns'] = 'dnsbl.njabl.org';
  782. $filters['NJABL DUL']['result'] = '127.0.0.3';
  783. $filters['NJABL DUL']['comment'] =
  784. _("FREE, for now - Not Just Another Blacklist - Dial-up IPs.");
  785. foreach ($filters as $Key => $Value) {
  786. $filters[$Key]['enabled'] = (bool)getPref($data_dir, $username, $filters[$Key]['prefname']);
  787. }
  788. return $filters;
  789. }
  790. /**
  791. * Removes a User filter
  792. * @param int $id ID of the filter to remove
  793. * @access private
  794. */
  795. function remove_filter ($id) {
  796. global $data_dir, $username;
  797. while ($nextFilter = getPref($data_dir, $username, 'filter' . ($id + 1))) {
  798. setPref($data_dir, $username, 'filter' . $id, $nextFilter);
  799. $id ++;
  800. }
  801. removePref($data_dir, $username, 'filter' . $id);
  802. }
  803. /**
  804. * Swaps two filters
  805. * @param int $id1 ID of first filter to swap
  806. * @param int $id2 ID of second filter to swap
  807. * @access private
  808. */
  809. function filter_swap($id1, $id2) {
  810. global $data_dir, $username;
  811. $FirstFilter = getPref($data_dir, $username, 'filter' . $id1);
  812. $SecondFilter = getPref($data_dir, $username, 'filter' . $id2);
  813. if ($FirstFilter && $SecondFilter) {
  814. setPref($data_dir, $username, 'filter' . $id2, $FirstFilter);
  815. setPref($data_dir, $username, 'filter' . $id1, $SecondFilter);
  816. }
  817. }
  818. /**
  819. * This updates the filter rules when renaming or deleting folders
  820. * @param array $args
  821. * @access private
  822. */
  823. function update_for_folder ($args) {
  824. $old_folder = $args[0];
  825. $new_folder = $args[2];
  826. $action = $args[1];
  827. global $data_dir, $username;
  828. $filters = array();
  829. $filters = load_filters();
  830. $filter_count = count($filters);
  831. $p = 0;
  832. for ($i = 0; $i < $filter_count; $i++) {
  833. if (!empty($filters)) {
  834. if ($old_folder == $filters[$i]['folder']) {
  835. if ($action == 'rename') {
  836. $filters[$i]['folder'] = $new_folder;
  837. setPref($data_dir, $username, 'filter'.$i,
  838. $filters[$i]['where'].','.$filters[$i]['what'].','.$new_folder);
  839. }
  840. elseif ($action == 'delete') {
  841. remove_filter($p);
  842. $p = $p-1;
  843. }
  844. }
  845. $p++;
  846. }
  847. }
  848. }
  849. /**
  850. * Display formated error message
  851. * @param string $string text message
  852. * @return string html formated text message
  853. * @access private
  854. */
  855. function do_error($string) {
  856. global $color;
  857. echo "<p align=\"center\"><font color=\"$color[2]\">";
  858. echo $string;
  859. echo "</font></p>\n";
  860. }