composer package updates
[openemr.git] / vendor / zendframework / zend-mail / src / Storage / Mbox.php
blob30de89cdca8700a694fed1162922ca9694ab92b2
1 <?php
2 /**
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
6 */
8 namespace Zend\Mail\Storage;
10 use Zend\Stdlib\ErrorHandler;
12 class Mbox extends AbstractStorage
14 /**
15 * file handle to mbox file
16 * @var null|resource
18 protected $fh;
20 /**
21 * filename of mbox file for __wakeup
22 * @var string
24 protected $filename;
26 /**
27 * modification date of mbox file for __wakeup
28 * @var int
30 protected $filemtime;
32 /**
33 * start and end position of messages as array('start' => start, 'separator' => headersep, 'end' => end)
34 * @var array
36 protected $positions;
38 /**
39 * used message class, change it in an extended class to extend the returned message class
40 * @var string
42 protected $messageClass = '\Zend\Mail\Storage\Message\File';
44 /**
45 * end of Line for messages
47 * @var string|null
49 protected $messageEOL;
51 /**
52 * Count messages all messages in current box
54 * @return int number of messages
55 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
57 public function countMessages()
59 return count($this->positions);
62 /**
63 * Get a list of messages with number and size
65 * @param int|null $id number of message or null for all messages
66 * @return int|array size of given message of list with all messages as array(num => size)
68 public function getSize($id = 0)
70 if ($id) {
71 $pos = $this->positions[$id - 1];
72 return $pos['end'] - $pos['start'];
75 $result = [];
76 foreach ($this->positions as $num => $pos) {
77 $result[$num + 1] = $pos['end'] - $pos['start'];
80 return $result;
83 /**
84 * Get positions for mail message or throw exception if id is invalid
86 * @param int $id number of message
87 * @throws Exception\InvalidArgumentException
88 * @return array positions as in positions
90 protected function getPos($id)
92 if (! isset($this->positions[$id - 1])) {
93 throw new Exception\InvalidArgumentException('id does not exist');
96 return $this->positions[$id - 1];
99 /**
100 * Fetch a message
102 * @param int $id number of message
103 * @return \Zend\Mail\Storage\Message\File
104 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
106 public function getMessage($id)
108 // TODO that's ugly, would be better to let the message class decide
109 if (strtolower($this->messageClass) == '\zend\mail\storage\message\file'
110 || is_subclass_of($this->messageClass, '\Zend\Mail\Storage\Message\File')) {
111 // TODO top/body lines
112 $messagePos = $this->getPos($id);
114 $messageClassParams = [
115 'file' => $this->fh,
116 'startPos' => $messagePos['start'],
117 'endPos' => $messagePos['end']
120 if (isset($this->messageEOL)) {
121 $messageClassParams['EOL'] = $this->messageEOL;
124 return new $this->messageClass($messageClassParams);
127 $bodyLines = 0; // TODO: need a way to change that
129 $message = $this->getRawHeader($id);
130 // file pointer is after headers now
131 if ($bodyLines) {
132 $message .= "\n";
133 while ($bodyLines-- && ftell($this->fh) < $this->positions[$id - 1]['end']) {
134 $message .= fgets($this->fh);
138 return new $this->messageClass(['handler' => $this, 'id' => $id, 'headers' => $message]);
142 * Get raw header of message or part
144 * @param int $id number of message
145 * @param null|array|string $part path to part or null for message header
146 * @param int $topLines include this many lines with header (after an empty line)
147 * @return string raw header
148 * @throws \Zend\Mail\Protocol\Exception\ExceptionInterface
149 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
151 public function getRawHeader($id, $part = null, $topLines = 0)
153 if ($part !== null) {
154 // TODO: implement
155 throw new Exception\RuntimeException('not implemented');
157 $messagePos = $this->getPos($id);
158 // TODO: toplines
159 return stream_get_contents($this->fh, $messagePos['separator'] - $messagePos['start'], $messagePos['start']);
163 * Get raw content of message or part
165 * @param int $id number of message
166 * @param null|array|string $part path to part or null for message content
167 * @return string raw content
168 * @throws \Zend\Mail\Protocol\Exception\ExceptionInterface
169 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
171 public function getRawContent($id, $part = null)
173 if ($part !== null) {
174 // TODO: implement
175 throw new Exception\RuntimeException('not implemented');
177 $messagePos = $this->getPos($id);
178 return stream_get_contents($this->fh, $messagePos['end'] - $messagePos['separator'], $messagePos['separator']);
182 * Create instance with parameters
183 * Supported parameters are:
184 * - filename filename of mbox file
186 * @param $params array mail reader specific parameters
187 * @throws Exception\InvalidArgumentException
189 public function __construct($params)
191 if (is_array($params)) {
192 $params = (object) $params;
195 if (! isset($params->filename)) {
196 throw new Exception\InvalidArgumentException('no valid filename given in params');
199 if (isset($params->messageEOL)) {
200 $this->messageEOL = (string) $params->messageEOL;
203 $this->openMboxFile($params->filename);
204 $this->has['top'] = true;
205 $this->has['uniqueid'] = false;
209 * check if given file is a mbox file
211 * if $file is a resource its file pointer is moved after the first line
213 * @param resource|string $file stream resource of name of file
214 * @param bool $fileIsString file is string or resource
215 * @return bool file is mbox file
217 protected function isMboxFile($file, $fileIsString = true)
219 if ($fileIsString) {
220 ErrorHandler::start(E_WARNING);
221 $file = fopen($file, 'r');
222 ErrorHandler::stop();
223 if (! $file) {
224 return false;
226 } else {
227 fseek($file, 0);
230 $result = false;
232 $line = fgets($file) ?: '';
233 if (strpos($line, 'From ') === 0) {
234 $result = true;
237 if ($fileIsString) {
238 ErrorHandler::start(E_WARNING);
239 fclose($file);
240 ErrorHandler::stop();
243 return $result;
247 * open given file as current mbox file
249 * @param string $filename filename of mbox file
250 * @throws Exception\RuntimeException
251 * @throws Exception\InvalidArgumentException
253 protected function openMboxFile($filename)
255 if ($this->fh) {
256 $this->close();
259 ErrorHandler::start();
260 $this->fh = fopen($filename, 'r');
261 $error = ErrorHandler::stop();
262 if (! $this->fh) {
263 throw new Exception\RuntimeException('cannot open mbox file', 0, $error);
265 $this->filename = $filename;
266 $this->filemtime = filemtime($this->filename);
268 if (! $this->isMboxFile($this->fh, false)) {
269 ErrorHandler::start(E_WARNING);
270 fclose($this->fh);
271 $error = ErrorHandler::stop();
272 throw new Exception\InvalidArgumentException('file is not a valid mbox format', 0, $error);
275 $messagePos = ['start' => ftell($this->fh), 'separator' => 0, 'end' => 0];
276 while (($line = fgets($this->fh)) !== false) {
277 if (strpos($line, 'From ') === 0) {
278 $messagePos['end'] = ftell($this->fh) - strlen($line) - 2; // + newline
279 if (! $messagePos['separator']) {
280 $messagePos['separator'] = $messagePos['end'];
282 $this->positions[] = $messagePos;
283 $messagePos = ['start' => ftell($this->fh), 'separator' => 0, 'end' => 0];
285 if (! $messagePos['separator'] && ! trim($line)) {
286 $messagePos['separator'] = ftell($this->fh);
290 $messagePos['end'] = ftell($this->fh);
291 if (! $messagePos['separator']) {
292 $messagePos['separator'] = $messagePos['end'];
294 $this->positions[] = $messagePos;
298 * Close resource for mail lib. If you need to control, when the resource
299 * is closed. Otherwise the destructor would call this.
302 public function close()
304 ErrorHandler::start(E_WARNING);
305 fclose($this->fh);
306 ErrorHandler::stop();
307 $this->positions = [];
312 * Waste some CPU cycles doing nothing.
314 * @return bool always return true
316 public function noop()
318 return true;
323 * stub for not supported message deletion
325 * @param $id
326 * @throws Exception\RuntimeException
328 public function removeMessage($id)
330 throw new Exception\RuntimeException('mbox is read-only');
334 * get unique id for one or all messages
336 * Mbox does not support unique ids (yet) - it's always the same as the message number.
337 * That shouldn't be a problem, because we can't change mbox files. Therefor the message
338 * number is save enough.
340 * @param int|null $id message number
341 * @return array|string message number for given message or all messages as array
342 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
344 public function getUniqueId($id = null)
346 if ($id) {
347 // check if id exists
348 $this->getPos($id);
349 return $id;
352 $range = range(1, $this->countMessages());
353 return array_combine($range, $range);
357 * get a message number from a unique id
359 * I.e. if you have a webmailer that supports deleting messages you should use unique ids
360 * as parameter and use this method to translate it to message number right before calling removeMessage()
362 * @param string $id unique id
363 * @return int message number
364 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
366 public function getNumberByUniqueId($id)
368 // check if id exists
369 $this->getPos($id);
370 return $id;
374 * magic method for serialize()
376 * with this method you can cache the mbox class
378 * @return array name of variables
380 public function __sleep()
382 return ['filename', 'positions', 'filemtime'];
386 * magic method for unserialize()
388 * with this method you can cache the mbox class
389 * for cache validation the mtime of the mbox file is used
391 * @throws Exception\RuntimeException
393 public function __wakeup()
395 ErrorHandler::start();
396 $filemtime = filemtime($this->filename);
397 ErrorHandler::stop();
398 if ($this->filemtime != $filemtime) {
399 $this->close();
400 $this->openMboxFile($this->filename);
401 } else {
402 ErrorHandler::start();
403 $this->fh = fopen($this->filename, 'r');
404 $error = ErrorHandler::stop();
405 if (! $this->fh) {
406 throw new Exception\RuntimeException('cannot open mbox file', 0, $error);