1<?php 2 3/* 4 * This file is part of SwiftMailer. 5 * (c) 2004-2009 Chris Corbyn 6 * 7 * For the full copyright and license information, please view the LICENSE 8 * file that was distributed with this source code. 9 */ 10 11/** 12 * Reduces network flooding when sending large amounts of mail. 13 * 14 * @author Chris Corbyn 15 */ 16class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_Plugins_Sleeper 17{ 18 /** 19 * The number of emails to send before restarting Transport. 20 * 21 * @var int 22 */ 23 private $_threshold; 24 25 /** 26 * The number of seconds to sleep for during a restart. 27 * 28 * @var int 29 */ 30 private $_sleep; 31 32 /** 33 * The internal counter. 34 * 35 * @var int 36 */ 37 private $_counter = 0; 38 39 /** 40 * The Sleeper instance for sleeping. 41 * 42 * @var Swift_Plugins_Sleeper 43 */ 44 private $_sleeper; 45 46 /** 47 * Create a new AntiFloodPlugin with $threshold and $sleep time. 48 * 49 * @param int $threshold 50 * @param int $sleep time 51 * @param Swift_Plugins_Sleeper $sleeper (not needed really) 52 */ 53 public function __construct($threshold = 99, $sleep = 0, Swift_Plugins_Sleeper $sleeper = null) 54 { 55 $this->setThreshold($threshold); 56 $this->setSleepTime($sleep); 57 $this->_sleeper = $sleeper; 58 } 59 60 /** 61 * Set the number of emails to send before restarting. 62 * 63 * @param int $threshold 64 */ 65 public function setThreshold($threshold) 66 { 67 $this->_threshold = $threshold; 68 } 69 70 /** 71 * Get the number of emails to send before restarting. 72 * 73 * @return int 74 */ 75 public function getThreshold() 76 { 77 return $this->_threshold; 78 } 79 80 /** 81 * Set the number of seconds to sleep for during a restart. 82 * 83 * @param int $sleep time 84 */ 85 public function setSleepTime($sleep) 86 { 87 $this->_sleep = $sleep; 88 } 89 90 /** 91 * Get the number of seconds to sleep for during a restart. 92 * 93 * @return int 94 */ 95 public function getSleepTime() 96 { 97 return $this->_sleep; 98 } 99 100 /** 101 * Invoked immediately before the Message is sent. 102 * 103 * @param Swift_Events_SendEvent $evt 104 */ 105 public function beforeSendPerformed(Swift_Events_SendEvent $evt) 106 { 107 } 108 109 /** 110 * Invoked immediately after the Message is sent. 111 * 112 * @param Swift_Events_SendEvent $evt 113 */ 114 public function sendPerformed(Swift_Events_SendEvent $evt) 115 { 116 ++$this->_counter; 117 if ($this->_counter >= $this->_threshold) { 118 $transport = $evt->getTransport(); 119 $transport->stop(); 120 if ($this->_sleep) { 121 $this->sleep($this->_sleep); 122 } 123 $transport->start(); 124 $this->_counter = 0; 125 } 126 } 127 128 /** 129 * Sleep for $seconds. 130 * 131 * @param int $seconds 132 */ 133 public function sleep($seconds) 134 { 135 if (isset($this->_sleeper)) { 136 $this->_sleeper->sleep($seconds); 137 } else { 138 sleep($seconds); 139 } 140 } 141} 142