1<?php
2
3/**
4 * Swift Mailer AntiFlood Plugin
5 * Please read the LICENSE file
6 * @author Chris Corbyn <chris@w3style.co.uk>
7 * @package Swift_Plugin
8 * @license GNU Lesser General Public License
9 */
10
11require_once dirname(__FILE__) . "/../ClassLoader.php";
12Swift_ClassLoader::load("Swift_Events_SendListener");
13
14/**
15 * Swift AntiFlood controller.
16 * Closes a connection and pauses for X seconds after a number of emails have been sent.
17 * @package Swift_Plugin
18 * @author Chris Corbyn <chris@w3style.co.uk>
19 */
20class Swift_Plugin_AntiFlood implements Swift_Events_SendListener
21{
22  /**
23   * The number of emails to send between connections
24   * @var int
25   */
26  protected $threshold = null;
27  /**
28   * The number of seconds to pause for between connections
29   * @var int
30   */
31  protected $waitFor = null;
32  /**
33   * Number of emails sent so far
34   * @var int
35   */
36  protected $count = 0;
37
38  /**
39   * Constructor
40   * @param int Number of emails to send before re-connecting
41   * @param int The timeout in seconds between connections
42   */
43  public function __construct($threshold, $wait=0)
44  {
45    $this->setThreshold($threshold);
46    $this->setWait($wait);
47  }
48  /**
49   * Set the number of emails which must be sent for a reconnection to occur
50   * @param int Number of emails
51   */
52  public function setThreshold($threshold)
53  {
54    $this->threshold = (int) $threshold;
55  }
56  /**
57   * Get the number of emails which need to be sent for reconnection to occur
58   * @return int
59   */
60  public function getThreshold()
61  {
62    return $this->threshold;
63  }
64  /**
65   * Set the number of seconds the plugin should wait for before reconnecting
66   * @param int Time in seconds
67   */
68  public function setWait($time)
69  {
70    $this->waitFor = (int) $time;
71  }
72  /**
73   * Get the number of seconds the plugin should wait for before re-connecting
74   * @return int
75   */
76  public function getWait()
77  {
78    return $this->waitFor;
79  }
80  /**
81   * Sleep for a given number of seconds
82   * @param int Number of seconds to wait for
83   */
84  public function wait($seconds)
85  {
86    if ($seconds) sleep($seconds);
87  }
88  /**
89   * Swift's SendEvent listener.
90   * Invoked when Swift sends a message
91   * @param Swift_Events_SendEvent The event information
92   * @throws Swift_ConnectionException If the connection cannot be closed/re-opened
93   */
94  public function sendPerformed(Swift_Events_SendEvent $e)
95  {
96    $this->count++;
97    if ($this->count >= $this->getThreshold())
98    {
99      $e->getSwift()->disconnect();
100      $this->wait($this->getWait());
101      $e->getSwift()->connect();
102      $this->count = 0;
103    }
104  }
105}
106