3 * @see https://github.com/zendframework/zend-mail for the canonical source repository
4 * @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (https://www.zend.com)
5 * @license https://github.com/zendframework/zend-mail/blob/master/LICENSE.md New BSD License
8 namespace Zend\Mail\Protocol
;
13 * Provides low-level methods for concrete adapters to communicate with a
14 * remote mail server and track requests and responses.
16 * @todo Implement proxy settings
18 abstract class AbstractProtocol
21 * Mail default EOL string
26 * Default timeout in seconds for initiating session
28 const TIMEOUT_CONNECTION
= 30;
31 * Maximum of the transaction log
34 protected $maximumLog = 64;
37 * Hostname or IP address of remote server
43 * Port number of connection
49 * Instance of Zend\Validator\ValidatorChain to check hostnames
50 * @var \Zend\Validator\ValidatorChain
55 * Socket connection resource
61 * Last request sent to server
67 * Array of server responses to last request
73 * Log of mail requests and server responses for a session
81 * @param string $host OPTIONAL Hostname of remote connection (default: 127.0.0.1)
82 * @param int $port OPTIONAL Port number (default: null)
83 * @throws Exception\RuntimeException
85 public function __construct($host = '127.0.0.1', $port = null)
87 $this->validHost
= new Validator\
ValidatorChain();
88 $this->validHost
->attach(new Validator\
Hostname(Validator\Hostname
::ALLOW_ALL
));
90 if (! $this->validHost
->isValid($host)) {
91 throw new Exception\
RuntimeException(implode(', ', $this->validHost
->getMessages()));
99 * Class destructor to cleanup open resources
102 public function __destruct()
104 $this->_disconnect();
108 * Set the maximum log size
110 * @param int $maximumLog Maximum log size
112 public function setMaximumLog($maximumLog)
114 $this->maximumLog
= (int) $maximumLog;
118 * Get the maximum log size
120 * @return int the maximum log size
122 public function getMaximumLog()
124 return $this->maximumLog
;
128 * Create a connection to the remote host
130 * Concrete adapters for this class will implement their own unique connect
131 * scripts, using the _connect() method to create the socket resource.
133 abstract public function connect();
136 * Retrieve the last client request
140 public function getRequest()
142 return $this->request
;
146 * Retrieve the last server response
150 public function getResponse()
152 return $this->response
;
156 * Retrieve the transaction log
160 public function getLog()
162 return implode('', $this->log
);
166 * Reset the transaction log
169 public function resetLog()
174 // @codingStandardsIgnoreStart
176 * Add the transaction log
178 * @param string $value new transaction
180 protected function _addLog($value)
182 // @codingStandardsIgnoreEnd
183 if ($this->maximumLog
>= 0 && count($this->log
) >= $this->maximumLog
) {
184 array_shift($this->log
);
187 $this->log
[] = $value;
190 // @codingStandardsIgnoreStart
192 * Connect to the server using the supplied transport and target
194 * An example $remote string may be 'tcp://mail.example.com:25' or 'ssh://hostname.com:2222'
196 * @param string $remote Remote
197 * @throws Exception\RuntimeException
200 protected function _connect($remote)
202 // @codingStandardsIgnoreEnd
208 function ($error, $message = '') {
209 throw new Exception\
RuntimeException(sprintf('Could not open socket: %s', $message), $error);
213 $this->socket
= stream_socket_client($remote, $errorNum, $errorStr, self
::TIMEOUT_CONNECTION
);
214 restore_error_handler();
216 if ($this->socket
=== false) {
217 if ($errorNum == 0) {
218 $errorStr = 'Could not open socket';
220 throw new Exception\
RuntimeException($errorStr);
223 if (($result = stream_set_timeout($this->socket
, self
::TIMEOUT_CONNECTION
)) === false) {
224 throw new Exception\
RuntimeException('Could not set stream timeout');
230 // @codingStandardsIgnoreStart
232 * Disconnect from remote host and free resource
235 protected function _disconnect()
237 // @codingStandardsIgnoreEnd
238 if (is_resource($this->socket
)) {
239 fclose($this->socket
);
243 // @codingStandardsIgnoreStart
245 * Send the given request followed by a LINEEND to the server.
247 * @param string $request
248 * @throws Exception\RuntimeException
249 * @return int|bool Number of bytes written to remote host
251 protected function _send($request)
253 // @codingStandardsIgnoreEnd
254 if (! is_resource($this->socket
)) {
255 throw new Exception\
RuntimeException('No connection has been established to ' . $this->host
);
258 $this->request
= $request;
260 $result = fwrite($this->socket
, $request . self
::EOL
);
262 // Save request to internal log
263 $this->_addLog($request . self
::EOL
);
265 if ($result === false) {
266 throw new Exception\
RuntimeException('Could not send request to ' . $this->host
);
272 // @codingStandardsIgnoreStart
274 * Get a line from the stream.
276 * @param int $timeout Per-request timeout value if applicable
277 * @throws Exception\RuntimeException
280 protected function _receive($timeout = null)
282 // @codingStandardsIgnoreEnd
283 if (! is_resource($this->socket
)) {
284 throw new Exception\
RuntimeException('No connection has been established to ' . $this->host
);
287 // Adapters may wish to supply per-commend timeouts according to appropriate RFC
288 if ($timeout !== null) {
289 stream_set_timeout($this->socket
, $timeout);
293 $response = fgets($this->socket
, 1024);
295 // Save request to internal log
296 $this->_addLog($response);
298 // Check meta data to ensure connection is still valid
299 $info = stream_get_meta_data($this->socket
);
301 if (! empty($info['timed_out'])) {
302 throw new Exception\
RuntimeException($this->host
. ' has timed out');
305 if ($response === false) {
306 throw new Exception\
RuntimeException('Could not read from ' . $this->host
);
312 // @codingStandardsIgnoreStart
314 * Parse server response for successful codes
316 * Read the response from the stream and check for expected return code.
317 * Throws a Zend\Mail\Protocol\Exception\ExceptionInterface if an unexpected code is returned.
319 * @param string|array $code One or more codes that indicate a successful response
320 * @param int $timeout Per-request timeout value if applicable
321 * @throws Exception\RuntimeException
322 * @return string Last line of response string
324 protected function _expect($code, $timeout = null)
326 // @codingStandardsIgnoreEnd
327 $this->response
= [];
330 if (! is_array($code)) {
335 $this->response
[] = $result = $this->_receive($timeout);
336 list($cmd, $more, $msg) = preg_split('/([\s-]+)/', $result, 2, PREG_SPLIT_DELIM_CAPTURE
);
338 if ($errMsg !== '') {
339 $errMsg .= ' ' . $msg;
340 } elseif ($cmd === null ||
! in_array($cmd, $code)) {
344 // The '-' message prefix indicates an information string instead of a response string.
345 } while (strpos($more, '-') === 0);
347 if ($errMsg !== '') {
348 throw new Exception\
RuntimeException($errMsg);