<?php
// $Id: sasql_hooks.php,v 1.32 2006/11/09 20:29:21 perlstalker Exp $

//error_reporting('E_ALL');

if (!defined ('SM_PATH')) { define('SM_PATH', '../../'); }
// This include breaks a lot of things for reasons I don't get.
#include_once(SM_PATH.'plugins/sasql/sasql_conf.php');

function sasql_special_folder_check ($box)
{
  // This only seems to work with include() but not include_once()
  // and, for some reason, I can't leave out the include and
  // use global.
  include(SM_PATH.'plugins/sasql/sasql_conf.php');

  //global $special_spam_folder, $spam_folder;
  //echo "Foo: $special_spam_folder<br>";
  if (! $special_spam_folder) { return 0; }

  global $folder_prefix;
  if ($box == $folder_prefix.$spam_folder) {
    return 1;
  } else if ($sasql_use_learn &&
	     ($box == $folder_prefix.$learn_spam_folder
              || $box == $folder_prefix.$learn_fp_folder)) {
    return 1;
  } else {
    return 0;
  }
}

function sasql_autocreate_spam_folder () {
  // This only seems to work with include() but not include_once().
  include(SM_PATH.'plugins/sasql/sasql_conf.php');

  //echo "Bar: $special_spam_folder";
  //global $special_spam_folder, $spam_folder;
  if (! $special_spam_folder) { return 0; }

  include_once(SM_PATH.'functions/imap.php');
  /* get those globals */

  sqgetGlobalVar('username', $username, SQ_SESSION);
  sqgetGlobalVar('key', $key, SQ_COOKIE);
  sqgetGlobalVar('delimiter', $delimiter, SQ_SESSION);
  sqgetGlobalVar('onetimepad', $onetimepad, SQ_SESSION);

  global $folder_prefix, $imapServerAddress, $imapPort;
  global $imap_server_type;

  global $sasql_use_learn;
  /* finished globals */

  if ($sasql_use_learn) {
    $boxes = array($spam_folder, $learn_spam_folder, $learn_fp_folder);
  } else {
    $boxes = array($spam_folder);
  }
  
  $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 0);

  foreach ($boxes as $box) {


    if (! $box or $box == '') {
      //echo "<foo sasql missing: $box />";
      continue;
    }

    $mailbox = $folder_prefix.$box;

    // echo "<foo sasql imap_server_type: $imap_server_type />";

    if (!sqimap_mailbox_exists($imap_stream, $mailbox)) {
      sqimap_mailbox_create($imap_stream, $mailbox, '');
      if ($imap_server_type == 'cyrus') {
	$boxes = sqimap_mailbox_list($imap_stream);
      } else {
	$boxes = sqimap_mailbox_list($imap_stream, true);
      }
      session_register($boxes, 'boxesnew');
      // echo "<foo sasql created: $box />";
    }

    if (!sqimap_mailbox_is_subscribed($imap_stream, $mailbox)) {
      sqimap_subscribe($imap_stream, $mailbox);
      if ($imap_server_type == 'cyrus') {
	$boxes = sqimap_mailbox_list($imap_stream);
      } else {
	$boxes = sqimap_mailbox_list($imap_stream, true);
      }
      session_register($boxes, 'boxesnew');
      // echo "<foo sasql subscried: $box />";
    }
  }

  sqimap_logout ($imap_stream);
  return 1;
}

function sasql_optpage_register_block () {
  global $optpage_blocks;

  // Set sasql gettext domain
  bindtextdomain ('sasql', SM_PATH . 'locale');
  textdomain ('sasql');

  $optpage_blocks[] =
    array (
	   'name' => _("Spam Filters"),
	   'url'  => '../plugins/sasql/sasql_options.php',
	   'desc' => _("Configure the behavior of your spam filters."),
	   'js'   => FALSE);

  // Set gettext domain back to squirrelmail.
  bindtextdomain ('squirrelmail', SM_PATH . 'locale');
  textdomain ('squirrelmail');
}

// Partially adapted from code submitted by Pa55wa11 <dugan@passwall.com>
// some of which he claims was stollen from the spamassassin plugin.
function sasql_add_sa_wblist () {
  include_once(SM_PATH.'plugins/sasql/sasql_conf.php');
  include_once(SM_PATH.'plugins/sasql/sasql_db.php');

  global $mailbox;   // Current mailbox
  global $passed_id; // Message id
  global $ent_id;    // Entity id (jump back to attachment)
  global $startMessage; // Paginator index.

  // Set sasql gettext domain
  bindtextdomain ('sasql', SM_PATH . 'locale');
  textdomain ('sasql');

  $sa_link = '';

  // SM stuff
  global $username, $message, $sent_folder;

  // sasql stuff
  global $SqlDSN, $SqlTable;
  global $use_quick_link;
  global $globalUsername;

  if (! $use_quick_link) {
    return;
  }

  // If we're in the Sent folder, then "our" address is the
  // from address.
  if ($mailbox == $sent_folder) {
    if (!isset($message->header->to)) {
      $safrom = $message->rfc822_header->getAddr_s('to');
    } else {
      $safrom = $message->header->to[0];
    }
  } else {
    if (!isset($message->header->from)
	|| empty($message->header->from)) {
      $safrom = $message->rfc822_header->getAddr_s('from');
    } else {
      $safrom = $message->header->from;
    }
  }

  // Get the address out of the header
  preg_match("/([.-\w]+@[A-Za-z0-9\.]+[A-Za-z0-9\.-]+\.[A-Za-z0-9]+)/",
	     $safrom, $from_matches);
  $chkfrom = $from_matches[1];
  // used if Black/White Listing entire domain
  $domPart = preg_split("/@/", $chkfrom);
  $blDomain = "*@" . $domPart[1];

  // Check for matches in the DB.
  $dbh = sasql_DBConnect($SqlDSN);
  if (DB::isError($dbh)) {
  } else {
    if ($safrom) {
      // Check whitelist
      $in_wlist = sasql_AddrInWBList ($dbh, $SqlTable, $username, 'w', $chkfrom);
      $in_gwlist = sasql_AddrInWBList ($dbh, $SqlTable, $globalUsername, 'w', $chkfrom);
      $in_wlDom = sasql_AddrInWBList ($dbh, $SqlTable, $username, 'w', $blDomain);
      $in_gwlDom = sasql_AddrInWBList ($dbh, $SqlTable, $globalUsername, 'w', $blDomain);
      // Check blacklist
      $in_blist = sasql_AddrInWBList ($dbh, $SqlTable, $username, 'b', $chkfrom);
      $in_gblist = sasql_AddrInWBList ($dbh, $SqlTable, $globalUsername, 'b', $chkfrom);
      $in_blDom = sasql_AddrInWBList ($dbh, $SqlTable, $username, 'b', $blDomain);
      $in_gblDom = sasql_AddrInWBList ($dbh, $SqlTable, $globalUsername, 'b', $blDomain);
    }
  }

  #error_log ("W: $in_wlist, GW: $in_gwlist, WD: $in_wlDom, GWD: $in_gwlDom");
  #error_log ("B: $in_blist, GB: $in_gblist, BD: $in_blDom, GBD: $in_gblDom");

  $sasql_optlink = "../plugins/sasql/sasql_options.php";
  $href = "../plugins/sasql/sasql_wblist.php?";
  $href .= "address=$chkfrom";
  $href .= "&mailbox=$mailbox";
  $href .= "&passed_id=$passed_id";
  $href .= "&startMessage=$startMessage";
  $dref = "../plugins/sasql/sasql_wblist.php?";
  $dref .= "address=$blDomain";
  $dref .= "&mailbox=$mailbox";
  $dref .= "&passed_id=$passed_id";
  $dref .= "&startMessage=$startMessage";
  if ($ent_id) { $href .= "&ent_id=$ent_id"; $dref .= "&ent_id=$ent_id"; }

  $wl_form = "<a title='"._('Add Email to Whitelist')."' href='$href";
  $wl_form .= "&action=new&preference=whitelist_from'>"._("Allow Sender")."</a>";
  $wl_formD = "<a title='"._('Add Domain to Whitelist')."' href='$dref";
  $wl_formD .= "&action=new&preference=whitelist_from'>"._("Allow Domain")."</a>";
  $wl_delf = "<a title='"._('Remove Email from Whitelist')."' href='$href";
  $wl_delf .= "&action=delete&preference=whitelist_from'>"._("remove")."</a>";
  $wl_delD = "<a title='"._('Remove Domain from Whitelist')."' href='$dref";
  $wl_delD .= "&action=delete&preference=whitelist_from'>"._("remove")."</a>";

  $bl_form = "<a title='"._('Add Email to Blacklist')."' href='$href";
  $bl_form .= "&action=new&preference=blacklist_from'>"._('Block Sender')."</a>";
  $bl_formD = "<a title='"._('Add Domain to Blacklist')."' href='$dref";
  $bl_formD .= "&action=new&preference=blacklist_from'>"._("Block Domain")."</a>";
  $bl_delf = "<a title='"._('Remove Email from Blacklist')."' href='$href";
  $bl_delf .= "&action=delete&preference=blacklist_from'>"._('remove')."</a>";
  $bl_delD = "<a title='"._('Remove Domain from Blacklist')."' href='$dref";
  $bl_delD .= "&action=delete&preference=blacklist_from'>"._('remove')."</a>";

  // Whitelist
  if ($in_wlist or $in_gwlist) {
    $sa_link .= '<a href="' . $sasql_optlink .
                '?viewsection=sa_whitelist&address=' . $chkfrom . '" title="' .
                _('Address is already in your whitelist') .
                '"><i>' . _("Whitelisted") . "</i></a> $chkfrom";
    if ($in_wlist) {
      $sa_link .= ' (' . $wl_delf . ')';
    }
  } elseif ($in_wlDom or $in_gwlDom) {
    $sa_link .= '<a href="' . $sasql_optlink .
                '?viewsection=sa_whitelist&address=' . $blDomain . '" title="' .
                _('Domain is already in your whitelist') .
                '"><i>' . _("Whitelisted") . "</i></a> $blDomain";
    if ($in_wlDom) {
      $sa_link .= ' (' . $wl_delD . ')';
    }
  } elseif (! $in_blist and ! $in_gblist) {
    //$sa_link .= $wl_form;
    $sa_link .= $wl_form.' | '.$wl_formD;
  }
  
  // Blacklist
  if ($in_blist or $in_gblist) {
    $sa_link .= '<a href="' . $sasql_optlink .
                '?viewsection=sa_whitelist&address=' . $chkfrom . '" title="' .
                _('Address is already in your blacklist'). '"><i>' .
                _("Blacklisted") . "</i></a> $chkfrom";
    if ($in_blist) {
      $sa_link .= ' (' . $bl_delf . ')';
    }
  } elseif ($in_blDom or $in_gblDom) {
    $sa_link .= ' | <a href="' . $sasql_optlink .
                '?viewsection=sa_whitelist&address=' . $blDomain . '" title="' .
                _('Domain is already in your blacklist'). '"><i>' .
                _("Blacklisted") . "</i></a> $blDomain";
    if ($in_blDom) {
      $sa_link .= ' (' . $bl_delD . ')';
    }
  } elseif (! $in_wlist and ! $in_gwlist) {
    $sa_link .= ' | '.$bl_form.' | '.$bl_formD;
  }

  if (isset($learn_spam_folder) and $learn_spam_folder
	and $sasql_use_learn and $sasql_learn_option) {
  	$sa_link .= sasql_report_spam_links_option();
  }

  // Set gettext domain back to squirrelmail.
  bindtextdomain ('squirrelmail', SM_PATH . 'locale');
  textdomain ('squirrelmail');

  echo '<tr><td align="right" valign="top" width="20%"><b>';
  echo _('Allow Sender');
  echo ':&nbsp;&nbsp;</b></td><td align="left" valign="top" width="80%">';

  echo '<small>',$sa_link,'</small>';

  echo '</td></tr>';
}

function sasql_report_spam_links_option() {
  // This only seems to work with include() but not include_once().
  include(SM_PATH.'plugins/sasql/sasql_conf.php');

  global $mailbox, $folder_prefix, $passed_id, $startMessage,
         $sort;

  // Set sasql gettext domain
  bindtextdomain ('sasql', SM_PATH . 'locale');
  textdomain ('sasql');

  $action= SM_PATH.'plugins/sasql/move_to.php?'
    ."mailbox=$mailbox"
    ."&sort=$sort"
    ."&startMessage=$startMessage";

  $show_button = 0;

  $targetMailbox = $folder_prefix;

  if (isset($learn_fp_folder) and $learn_fp_folder
      && $mailbox == $folder_prefix.$spam_folder) {
    $targetMailbox .= $learn_fp_folder;
    $submit = _('Learn as False Positive');
    $show_button = 1;
  } elseif (isset($learn_spam_folder) and $learn_spam_folder) {
    $targetMailbox .= $learn_spam_folder;
    $submit = _('Learn as Spam');
    $show_button = 1;
  }

  $action .= "&move_id=$passed_id";
  $action .= "&targetMailbox=$targetMailbox";
  $action .= "&location=../../src/right_main.php";

  $action= "&nbsp;|&nbsp;<a title='$submit' href='$action'>$submit</a>";

    if ($mailbox != $folder_prefix.$learn_spam_folder
	&& $mailbox != $folder_prefix.$learn_fp_folder) {
      return "$action";
    }
    else {
	    return "";
    }

  // Set gettext domain back to squirrelmail.
  bindtextdomain ('squirrelmail', SM_PATH . 'locale');
  textdomain ('squirrelmail');
}

function sasql_report_spam_links() {
  // This only seems to work with include() but not include_once().
  include(SM_PATH.'plugins/sasql/sasql_conf.php');

  global $mailbox, $folder_prefix, $passed_id, $startMessage,
         $sort;
  #global $sasql_use_learn;

  if (! $sasql_use_learn) {
    return;
  }
  if ($sasql_learn_option) {
    return;
  }

  // Set sasql gettext domain
  bindtextdomain ('sasql', SM_PATH . 'locale');
  textdomain ('sasql');

  //$action= 'right_main.php?'
  $action= SM_PATH.'plugins/sasql/move_to.php?'
    ."mailbox=$mailbox"
    ."&sort=$sort"
    ."&startMessage=$startMessage";

  $show_button = 0;

  $targetMailbox = $folder_prefix;
  if (isset($learn_fp_folder) and $learn_fp_folder
      && $mailbox == $folder_prefix.$spam_folder) {
    $targetMailbox .= $learn_fp_folder;
    $submit = _('Learn as False Positive');
    $show_button = 1;
  } elseif (isset($learn_spam_folder) and $learn_spam_folder) {
    $targetMailbox .= $learn_spam_folder;
    $submit = _('Learn as Spam');
    $show_button = 1;
  }

  // Don't show the button if only one learning folder is configured
  // and this isn't it.
  if ($show_button) {
    $form = "<form action='$action' method='Post'>";
    $form .= "<input type='hidden' name='mailbox' value='$mailbox' />";
    $form .= "<input type='hidden' name='sort' value='$sort' />";
    $form .= "<input type='hidden' name='startMessage' value='$startMessage' />";
    $form .= "<input type='hidden' name='move_id' value='$passed_id' />";
    $form .= "<input type='hidden' name='targetMailbox' value='$targetMailbox' />";
    $form .= "<input type='hidden' name='location' value='../../src/right_main.php' />";
    $form .= "<input type='submit' value='$submit' />";
    $form .= '</form>';

    echo '<table width="100%" border="0"><tr>';
    echo "<td align='center'>";
    if ($mailbox != $folder_prefix.$learn_spam_folder
	&& $mailbox != $folder_prefix.$learn_fp_folder) {
      echo $form;
    }
    echo "</td></tr></table>";
  }

  // Set gettext domain back to squirrelmail.
  bindtextdomain ('squirrelmail', SM_PATH . 'locale');
  textdomain ('squirrelmail');
}

function sasql_add_sa_score() {
  // This only seems to work with include() but not include_once().
  include(SM_PATH.'plugins/sasql/sasql_conf.php');

  // Set sasql gettext domain
  bindtextdomain ('sasql', SM_PATH . 'locale');
  textdomain ('sasql');

  global $message;

  if ($show_spam_report) {

      // echo sm_print_r($message);

      $score = $message->rfc822_header->x_spam_status['score'];
      $required = $message->rfc822_header->x_spam_status['required'];

      if (! isset($required) ) { return; }

      $spam_percent = 0;
      if ($required == 0) {
          if ($score > $required) {
              $spam_percent = 100;
          } else {
              $spam_percent = 0;
          }
      } else {
          $spam_percent = (int) ($score/$required*100);
      }

      $spam_color = 'white';
      if ($spam_percent <= 0) {
          $spam_color = '#ffffff';
      } else if ($spam_percent < 50) {
          $spam_color = 'green';
      } else if ($spam_percent < 80) {
          $spam_color = 'yellow';
      } else if ($spam_percent < 95) {
          $spam_color = 'orange';
      } else {
          $spam_color = 'red';
      }

      // read_body_header hook looks for output like <tr><td></td><td></td></tr>
  
      echo '<tr><td align="right" width="20%"><b>';
      echo _('Spam Score');
      echo ':&nbsp;&nbsp;</b></td><td align="left" valign="top" width="80%">';

      if ($spam_percent < 0) { $spam_percent = 1; }
      else if ($spam_percent > 100) { $spam_percent = 100; }

      echo  "<table border='0'><tr>";
      echo  '<td>';
      echo   '<table border="1" cellspacing="0">';
      echo    '<tr><td>';
      echo     '<table width="200" border="0">';
      echo      "<tr><td width='";
      echo $spam_percent;
      echo "%' bgcolor='$spam_color'>&nbsp;</td>";
      if ($spam_percent < 100) {
          echo "<td width='";
          echo 100 - $spam_percent;
          echo "%'></td>";
      }
      echo       '</tr>';
      echo      '</table>';
      echo     '</td></tr>';
      echo    '</table>';
      if ($show_report_score) {
          echo   '</td><td>';
          echo $score, '/', $required;
          echo   '</td></tr>';
      }
      echo  '</table>';
      echo '</td></tr>';
  }

  // Set gettext domain back to squirrelmail.
  bindtextdomain ('squirrelmail', SM_PATH . 'locale');
  textdomain ('squirrelmail');
}
