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 public function beforeSendPerformed(Swift_Events_SendEvent $evt) 104 { 105 } 106 107 /** 108 * Invoked immediately after the Message is sent. 109 */ 110 public function sendPerformed(Swift_Events_SendEvent $evt) 111 { 112 ++$this->counter; 113 if ($this->counter >= $this->threshold) { 114 $transport = $evt->getTransport(); 115 $transport->stop(); 116 if ($this->sleep) { 117 $this->sleep($this->sleep); 118 } 119 $transport->start(); 120 $this->counter = 0; 121 } 122 } 123 124 /** 125 * Sleep for $seconds. 126 * 127 * @param int $seconds 128 */ 129 public function sleep($seconds) 130 { 131 if (isset($this->sleeper)) { 132 $this->sleeper->sleep($seconds); 133 } else { 134 sleep($seconds); 135 } 136 } 137} 138