composer package updates
[openemr.git] / vendor / zendframework / zend-mail / src / Storage / Writable / Maildir.php
blob0a396b21efd74d6a6322e3802d4a24cd2df5be2e
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\Writable;
10 use RecursiveIteratorIterator;
11 use Zend\Mail\Exception as MailException;
12 use Zend\Mail\Storage;
13 use Zend\Mail\Storage\Exception as StorageException;
14 use Zend\Mail\Storage\Folder;
15 use Zend\Stdlib\ErrorHandler;
17 class Maildir extends Folder\Maildir implements WritableInterface
19 // TODO: init maildir (+ constructor option create if not found)
21 /**
22 * use quota and size of quota if given
24 * @var bool|int
26 protected $quota;
28 /**
29 * create a new maildir
31 * If the given dir is already a valid maildir this will not fail.
33 * @param string $dir directory for the new maildir (may already exist)
34 * @throws \Zend\Mail\Storage\Exception\RuntimeException
35 * @throws \Zend\Mail\Storage\Exception\InvalidArgumentException
37 public static function initMaildir($dir)
39 if (file_exists($dir)) {
40 if (! is_dir($dir)) {
41 throw new StorageException\InvalidArgumentException('maildir must be a directory if already exists');
43 } else {
44 ErrorHandler::start();
45 $test = mkdir($dir);
46 $error = ErrorHandler::stop();
47 if (! $test) {
48 $dir = dirname($dir);
49 if (! file_exists($dir)) {
50 throw new StorageException\InvalidArgumentException("parent $dir not found", 0, $error);
51 } elseif (! is_dir($dir)) {
52 throw new StorageException\InvalidArgumentException("parent $dir not a directory", 0, $error);
53 } else {
54 throw new StorageException\RuntimeException('cannot create maildir', 0, $error);
59 foreach (['cur', 'tmp', 'new'] as $subdir) {
60 ErrorHandler::start();
61 $test = mkdir($dir . DIRECTORY_SEPARATOR . $subdir);
62 $error = ErrorHandler::stop();
63 if (! $test) {
64 // ignore if dir exists (i.e. was already valid maildir or two processes try to create one)
65 if (! file_exists($dir . DIRECTORY_SEPARATOR . $subdir)) {
66 throw new StorageException\RuntimeException('could not create subdir ' . $subdir, 0, $error);
72 /**
73 * Create instance with parameters
74 * Additional parameters are (see parent for more):
75 * - create if true a new maildir is create if none exists
77 * @param $params array mail reader specific parameters
78 * @throws \Zend\Mail\Storage\Exception\ExceptionInterface
80 public function __construct($params)
82 if (is_array($params)) {
83 $params = (object) $params;
86 if (! empty($params->create)
87 && isset($params->dirname)
88 && ! file_exists($params->dirname . DIRECTORY_SEPARATOR . 'cur')
89 ) {
90 self::initMaildir($params->dirname);
93 parent::__construct($params);
96 /**
97 * create a new folder
99 * This method also creates parent folders if necessary. Some mail storages may restrict, which folder
100 * may be used as parent or which chars may be used in the folder name
102 * @param string $name global name of folder, local name if $parentFolder is set
103 * @param string|\Zend\Mail\Storage\Folder $parentFolder parent folder for new folder, else root folder is parent
104 * @throws \Zend\Mail\Storage\Exception\RuntimeException
105 * @return string only used internally (new created maildir)
107 public function createFolder($name, $parentFolder = null)
109 if ($parentFolder instanceof Folder) {
110 $folder = $parentFolder->getGlobalName() . $this->delim . $name;
111 } elseif ($parentFolder !== null) {
112 $folder = rtrim($parentFolder, $this->delim) . $this->delim . $name;
113 } else {
114 $folder = $name;
117 $folder = trim($folder, $this->delim);
119 // first we check if we try to create a folder that does exist
120 $exists = null;
121 try {
122 $exists = $this->getFolders($folder);
123 } catch (MailException\ExceptionInterface $e) {
124 // ok
126 if ($exists) {
127 throw new StorageException\RuntimeException('folder already exists');
130 if (strpos($folder, $this->delim . $this->delim) !== false) {
131 throw new StorageException\RuntimeException('invalid name - folder parts may not be empty');
134 if (strpos($folder, 'INBOX' . $this->delim) === 0) {
135 $folder = substr($folder, 6);
138 $fulldir = $this->rootdir . '.' . $folder;
140 // check if we got tricked and would create a dir outside of the rootdir or not as direct child
141 if (strpos($folder, DIRECTORY_SEPARATOR) !== false || strpos($folder, '/') !== false
142 || dirname($fulldir) . DIRECTORY_SEPARATOR != $this->rootdir
144 throw new StorageException\RuntimeException('invalid name - no directory separator allowed in folder name');
147 // has a parent folder?
148 $parent = null;
149 if (strpos($folder, $this->delim)) {
150 // let's see if the parent folder exists
151 $parent = substr($folder, 0, strrpos($folder, $this->delim));
152 try {
153 $this->getFolders($parent);
154 } catch (MailException\ExceptionInterface $e) {
155 // does not - create parent folder
156 $this->createFolder($parent);
160 ErrorHandler::start();
161 if (! mkdir($fulldir) || ! mkdir($fulldir . DIRECTORY_SEPARATOR . 'cur')) {
162 $error = ErrorHandler::stop();
163 throw new StorageException\RuntimeException(
164 'error while creating new folder, may be created incompletely',
166 $error
169 ErrorHandler::stop();
171 mkdir($fulldir . DIRECTORY_SEPARATOR . 'new');
172 mkdir($fulldir . DIRECTORY_SEPARATOR . 'tmp');
174 $localName = $parent ? substr($folder, strlen($parent) + 1) : $folder;
175 $this->getFolders($parent)->$localName = new Folder($localName, $folder, true);
177 return $fulldir;
181 * remove a folder
183 * @param string|Folder $name name or instance of folder
184 * @throws \Zend\Mail\Storage\Exception\RuntimeException
186 public function removeFolder($name)
188 // TODO: This could fail in the middle of the task, which is not optimal.
189 // But there is no defined standard way to mark a folder as removed and there is no atomar fs-op
190 // to remove a directory. Also moving the folder to a/the trash folder is not possible, as
191 // all parent folders must be created. What we could do is add a dash to the front of the
192 // directory name and it should be ignored as long as other processes obey the standard.
194 if ($name instanceof Folder) {
195 $name = $name->getGlobalName();
198 $name = trim($name, $this->delim);
199 if (strpos($name, 'INBOX' . $this->delim) === 0) {
200 $name = substr($name, 6);
203 // check if folder exists and has no children
204 if (! $this->getFolders($name)->isLeaf()) {
205 throw new StorageException\RuntimeException('delete children first');
208 if ($name == 'INBOX' || $name == DIRECTORY_SEPARATOR || $name == '/') {
209 throw new StorageException\RuntimeException('wont delete INBOX');
212 if ($name == $this->getCurrentFolder()) {
213 throw new StorageException\RuntimeException('wont delete selected folder');
216 foreach (['tmp', 'new', 'cur', '.'] as $subdir) {
217 $dir = $this->rootdir . '.' . $name . DIRECTORY_SEPARATOR . $subdir;
218 if (! file_exists($dir)) {
219 continue;
221 $dh = opendir($dir);
222 if (! $dh) {
223 throw new StorageException\RuntimeException("error opening $subdir");
225 while (($entry = readdir($dh)) !== false) {
226 if ($entry == '.' || $entry == '..') {
227 continue;
229 if (! unlink($dir . DIRECTORY_SEPARATOR . $entry)) {
230 throw new StorageException\RuntimeException("error cleaning $subdir");
233 closedir($dh);
234 if ($subdir !== '.') {
235 if (! rmdir($dir)) {
236 throw new StorageException\RuntimeException("error removing $subdir");
241 if (! rmdir($this->rootdir . '.' . $name)) {
242 // at least we should try to make it a valid maildir again
243 mkdir($this->rootdir . '.' . $name . DIRECTORY_SEPARATOR . 'cur');
244 throw new StorageException\RuntimeException("error removing maindir");
247 $parent = strpos($name, $this->delim) ? substr($name, 0, strrpos($name, $this->delim)) : null;
248 $localName = $parent ? substr($name, strlen($parent) + 1) : $name;
249 unset($this->getFolders($parent)->$localName);
253 * rename and/or move folder
255 * The new name has the same restrictions as in createFolder()
257 * @param string|\Zend\Mail\Storage\Folder $oldName name or instance of folder
258 * @param string $newName new global name of folder
259 * @throws \Zend\Mail\Storage\Exception\RuntimeException
261 public function renameFolder($oldName, $newName)
263 // TODO: This is also not atomar and has similar problems as removeFolder()
265 if ($oldName instanceof Folder) {
266 $oldName = $oldName->getGlobalName();
269 $oldName = trim($oldName, $this->delim);
270 if (strpos($oldName, 'INBOX' . $this->delim) === 0) {
271 $oldName = substr($oldName, 6);
274 $newName = trim($newName, $this->delim);
275 if (strpos($newName, 'INBOX' . $this->delim) === 0) {
276 $newName = substr($newName, 6);
279 if (strpos($newName, $oldName . $this->delim) === 0) {
280 throw new StorageException\RuntimeException('new folder cannot be a child of old folder');
283 // check if folder exists and has no children
284 $folder = $this->getFolders($oldName);
286 if ($oldName == 'INBOX' || $oldName == DIRECTORY_SEPARATOR || $oldName == '/') {
287 throw new StorageException\RuntimeException('wont rename INBOX');
290 if ($oldName == $this->getCurrentFolder()) {
291 throw new StorageException\RuntimeException('wont rename selected folder');
294 $newdir = $this->createFolder($newName);
296 if (! $folder->isLeaf()) {
297 foreach ($folder as $k => $v) {
298 $this->renameFolder($v->getGlobalName(), $newName . $this->delim . $k);
302 $olddir = $this->rootdir . '.' . $folder;
303 foreach (['tmp', 'new', 'cur'] as $subdir) {
304 $subdir = DIRECTORY_SEPARATOR . $subdir;
305 if (! file_exists($olddir . $subdir)) {
306 continue;
308 // using copy or moving files would be even better - but also much slower
309 if (! rename($olddir . $subdir, $newdir . $subdir)) {
310 throw new StorageException\RuntimeException('error while moving ' . $subdir);
313 // create a dummy if removing fails - otherwise we can't read it next time
314 mkdir($olddir . DIRECTORY_SEPARATOR . 'cur');
315 $this->removeFolder($oldName);
319 * create a uniqueid for maildir filename
321 * This is nearly the format defined in the maildir standard. The microtime() call should already
322 * create a uniqueid, the pid is for multicore/-cpu machine that manage to call this function at the
323 * exact same time, and uname() gives us the hostname for multiple machines accessing the same storage.
325 * If someone disables posix we create a random number of the same size, so this method should also
326 * work on Windows - if you manage to get maildir working on Windows.
327 * Microtime could also be disabled, although I've never seen it.
329 * @return string new uniqueid
331 protected function createUniqueId()
333 $id = '';
334 $id .= microtime(true);
335 $id .= '.' . getmypid();
336 $id .= '.' . php_uname('n');
338 return $id;
342 * open a temporary maildir file
344 * makes sure tmp/ exists and create a file with a unique name
345 * you should close the returned filehandle!
347 * @param string $folder name of current folder without leading .
348 * @throws \Zend\Mail\Storage\Exception\RuntimeException
349 * @return array array('dirname' => dir of maildir folder, 'uniq' => unique id, 'filename' => name of create file
350 * 'handle' => file opened for writing)
352 protected function createTmpFile($folder = 'INBOX')
354 if ($folder == 'INBOX') {
355 $tmpdir = $this->rootdir . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
356 } else {
357 $tmpdir = $this->rootdir . '.' . $folder . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
359 if (! file_exists($tmpdir)) {
360 if (! mkdir($tmpdir)) {
361 throw new StorageException\RuntimeException('problems creating tmp dir');
365 // we should retry to create a unique id if a file with the same name exists
366 // to avoid a script timeout we only wait 1 second (instead of 2) and stop
367 // after a defined retry count
368 // if you change this variable take into account that it can take up to $maxTries seconds
369 // normally we should have a valid unique name after the first try, we're just following the "standard" here
370 $maxTries = 5;
371 for ($i = 0; $i < $maxTries; ++$i) {
372 $uniq = $this->createUniqueId();
373 if (! file_exists($tmpdir . $uniq)) {
374 // here is the race condition! - as defined in the standard
375 // to avoid having a long time between stat()ing the file and creating it we're opening it here
376 // to mark the filename as taken
377 $fh = fopen($tmpdir . $uniq, 'w');
378 if (! $fh) {
379 throw new StorageException\RuntimeException('could not open temp file');
381 break;
383 sleep(1);
386 if (! $fh) {
387 throw new StorageException\RuntimeException(
388 "tried {$maxTries} unique ids for a temp file, but all were taken - giving up"
392 return ['dirname' => $this->rootdir . '.' . $folder,
393 'uniq' => $uniq,
394 'filename' => $tmpdir . $uniq,
395 'handle' => $fh];
399 * create an info string for filenames with given flags
401 * @param array $flags wanted flags, with the reference you'll get the set
402 * flags with correct key (= char for flag)
403 * @return string info string for version 2 filenames including the leading colon
404 * @throws StorageException\InvalidArgumentException
406 protected function getInfoString(&$flags)
408 // accessing keys is easier, faster and it removes duplicated flags
409 $wantedFlags = array_flip($flags);
410 if (isset($wantedFlags[Storage::FLAG_RECENT])) {
411 throw new StorageException\InvalidArgumentException('recent flag may not be set');
414 $info = ':2,';
415 $flags = [];
416 foreach (Storage\Maildir::$knownFlags as $char => $flag) {
417 if (! isset($wantedFlags[$flag])) {
418 continue;
420 $info .= $char;
421 $flags[$char] = $flag;
422 unset($wantedFlags[$flag]);
425 if (! empty($wantedFlags)) {
426 $wantedFlags = implode(', ', array_keys($wantedFlags));
427 throw new StorageException\InvalidArgumentException('unknown flag(s): ' . $wantedFlags);
430 return $info;
434 * append a new message to mail storage
436 * @param string|resource $message message as string or stream resource.
437 * @param null|string|Folder $folder folder for new message, else current
438 * folder is taken.
439 * @param null|array $flags set flags for new message, else a default set
440 * is used.
441 * @param bool $recent handle this mail as if recent flag has been set,
442 * should only be used in delivery.
443 * @throws StorageException\RuntimeException
445 public function appendMessage($message, $folder = null, $flags = null, $recent = false)
447 if ($this->quota && $this->checkQuota()) {
448 throw new StorageException\RuntimeException('storage is over quota!');
451 if ($folder === null) {
452 $folder = $this->currentFolder;
455 if (! ($folder instanceof Folder)) {
456 $folder = $this->getFolders($folder);
459 if ($flags === null) {
460 $flags = [Storage::FLAG_SEEN];
462 $info = $this->getInfoString($flags);
463 $tempFile = $this->createTmpFile($folder->getGlobalName());
465 // TODO: handle class instances for $message
466 if (is_resource($message) && get_resource_type($message) == 'stream') {
467 stream_copy_to_stream($message, $tempFile['handle']);
468 } else {
469 fwrite($tempFile['handle'], $message);
471 fclose($tempFile['handle']);
473 // we're adding the size to the filename for maildir++
474 $size = filesize($tempFile['filename']);
475 if ($size !== false) {
476 $info = ',S=' . $size . $info;
478 $newFilename = $tempFile['dirname'] . DIRECTORY_SEPARATOR;
479 $newFilename .= $recent ? 'new' : 'cur';
480 $newFilename .= DIRECTORY_SEPARATOR . $tempFile['uniq'] . $info;
482 // we're throwing any exception after removing our temp file and saving it to this variable instead
483 $exception = null;
485 if (! link($tempFile['filename'], $newFilename)) {
486 $exception = new StorageException\RuntimeException('cannot link message file to final dir');
489 ErrorHandler::start(E_WARNING);
490 unlink($tempFile['filename']);
491 ErrorHandler::stop();
493 if ($exception) {
494 throw $exception;
497 $this->files[] = ['uniq' => $tempFile['uniq'],
498 'flags' => $flags,
499 'filename' => $newFilename];
500 if ($this->quota) {
501 $this->addQuotaEntry((int) $size, 1);
506 * copy an existing message
508 * @param int $id number of message
509 * @param string|\Zend\Mail\Storage\Folder $folder name or instance of targer folder
510 * @throws \Zend\Mail\Storage\Exception\RuntimeException
512 public function copyMessage($id, $folder)
514 if ($this->quota && $this->checkQuota()) {
515 throw new StorageException\RuntimeException('storage is over quota!');
518 if (! ($folder instanceof Folder)) {
519 $folder = $this->getFolders($folder);
522 $filedata = $this->getFileData($id);
523 $oldFile = $filedata['filename'];
524 $flags = $filedata['flags'];
526 // copied message can't be recent
527 while (($key = array_search(Storage::FLAG_RECENT, $flags)) !== false) {
528 unset($flags[$key]);
530 $info = $this->getInfoString($flags);
532 // we're creating the copy as temp file before moving to cur/
533 $tempFile = $this->createTmpFile($folder->getGlobalName());
534 // we don't write directly to the file
535 fclose($tempFile['handle']);
537 // we're adding the size to the filename for maildir++
538 $size = filesize($oldFile);
539 if ($size !== false) {
540 $info = ',S=' . $size . $info;
543 $newFile = $tempFile['dirname'] . DIRECTORY_SEPARATOR . 'cur' . DIRECTORY_SEPARATOR . $tempFile['uniq'] . $info;
545 // we're throwing any exception after removing our temp file and saving it to this variable instead
546 $exception = null;
548 if (! copy($oldFile, $tempFile['filename'])) {
549 $exception = new StorageException\RuntimeException('cannot copy message file');
550 } elseif (! link($tempFile['filename'], $newFile)) {
551 $exception = new StorageException\RuntimeException('cannot link message file to final dir');
554 ErrorHandler::start(E_WARNING);
555 unlink($tempFile['filename']);
556 ErrorHandler::stop();
558 if ($exception) {
559 throw $exception;
562 if ($folder->getGlobalName() == $this->currentFolder
563 || ($this->currentFolder == 'INBOX' && $folder->getGlobalName() == '/')
565 $this->files[] = ['uniq' => $tempFile['uniq'],
566 'flags' => $flags,
567 'filename' => $newFile];
570 if ($this->quota) {
571 $this->addQuotaEntry((int) $size, 1);
576 * move an existing message
578 * @param int $id number of message
579 * @param string|\Zend\Mail\Storage\Folder $folder name or instance of targer folder
580 * @throws \Zend\Mail\Storage\Exception\RuntimeException
582 public function moveMessage($id, $folder)
584 if (! ($folder instanceof Folder)) {
585 $folder = $this->getFolders($folder);
588 if ($folder->getGlobalName() == $this->currentFolder
589 || ($this->currentFolder == 'INBOX' && $folder->getGlobalName() == '/')
591 throw new StorageException\RuntimeException('target is current folder');
594 $filedata = $this->getFileData($id);
595 $oldFile = $filedata['filename'];
596 $flags = $filedata['flags'];
598 // moved message can't be recent
599 while (($key = array_search(Storage::FLAG_RECENT, $flags)) !== false) {
600 unset($flags[$key]);
602 $info = $this->getInfoString($flags);
604 // reserving a new name
605 $tempFile = $this->createTmpFile($folder->getGlobalName());
606 fclose($tempFile['handle']);
608 // we're adding the size to the filename for maildir++
609 $size = filesize($oldFile);
610 if ($size !== false) {
611 $info = ',S=' . $size . $info;
614 $newFile = $tempFile['dirname'] . DIRECTORY_SEPARATOR . 'cur' . DIRECTORY_SEPARATOR . $tempFile['uniq'] . $info;
616 // we're throwing any exception after removing our temp file and saving it to this variable instead
617 $exception = null;
619 if (! rename($oldFile, $newFile)) {
620 $exception = new StorageException\RuntimeException('cannot move message file');
623 ErrorHandler::start(E_WARNING);
624 unlink($tempFile['filename']);
625 ErrorHandler::stop();
627 if ($exception) {
628 throw $exception;
631 unset($this->files[$id - 1]);
632 // remove the gap
633 $this->files = array_values($this->files);
637 * set flags for message
639 * NOTE: this method can't set the recent flag.
641 * @param int $id number of message
642 * @param array $flags new flags for message
643 * @throws \Zend\Mail\Storage\Exception\RuntimeException
645 public function setFlags($id, $flags)
647 $info = $this->getInfoString($flags);
648 $filedata = $this->getFileData($id);
650 // NOTE: double dirname to make sure we always move to cur. if recent
651 // flag has been set (message is in new) it will be moved to cur.
652 $newFilename = dirname(dirname($filedata['filename']))
653 . DIRECTORY_SEPARATOR
654 . 'cur'
655 . DIRECTORY_SEPARATOR
656 . "$filedata[uniq]$info";
658 ErrorHandler::start();
659 $test = rename($filedata['filename'], $newFilename);
660 $error = ErrorHandler::stop();
661 if (! $test) {
662 throw new StorageException\RuntimeException('cannot rename file', 0, $error);
665 $filedata['flags'] = $flags;
666 $filedata['filename'] = $newFilename;
668 $this->files[$id - 1] = $filedata;
672 * stub for not supported message deletion
674 * @param $id
675 * @throws \Zend\Mail\Storage\Exception\RuntimeException
677 public function removeMessage($id)
679 $filename = $this->getFileData($id, 'filename');
681 if ($this->quota) {
682 $size = filesize($filename);
685 ErrorHandler::start();
686 $test = unlink($filename);
687 $error = ErrorHandler::stop();
688 if (! $test) {
689 throw new StorageException\RuntimeException('cannot remove message', 0, $error);
691 unset($this->files[$id - 1]);
692 // remove the gap
693 $this->files = array_values($this->files);
694 if ($this->quota) {
695 $this->addQuotaEntry(0 - (int) $size, -1);
700 * enable/disable quota and set a quota value if wanted or needed
702 * You can enable/disable quota with true/false. If you don't have
703 * a MDA or want to enforce a quota value you can also set this value
704 * here. Use array('size' => SIZE_QUOTA, 'count' => MAX_MESSAGE) do
705 * define your quota. Order of these fields does matter!
707 * @param bool|array $value new quota value
709 public function setQuota($value)
711 $this->quota = $value;
715 * get currently set quota
717 * @see \Zend\Mail\Storage\Writable\Maildir::setQuota()
718 * @param bool $fromStorage
719 * @throws \Zend\Mail\Storage\Exception\RuntimeException
720 * @return bool|array
722 public function getQuota($fromStorage = false)
724 if ($fromStorage) {
725 ErrorHandler::start(E_WARNING);
726 $fh = fopen($this->rootdir . 'maildirsize', 'r');
727 $error = ErrorHandler::stop();
728 if (! $fh) {
729 throw new StorageException\RuntimeException('cannot open maildirsize', 0, $error);
731 $definition = fgets($fh);
732 fclose($fh);
733 $definition = explode(',', trim($definition));
734 $quota = [];
735 foreach ($definition as $member) {
736 $key = $member[strlen($member) - 1];
737 if ($key == 'S' || $key == 'C') {
738 $key = $key == 'C' ? 'count' : 'size';
740 $quota[$key] = substr($member, 0, -1);
742 return $quota;
745 return $this->quota;
749 * @see http://www.inter7.com/courierimap/README.maildirquota.html "Calculating maildirsize"
750 * @throws \Zend\Mail\Storage\Exception\RuntimeException
751 * @return array
753 protected function calculateMaildirsize()
755 $timestamps = [];
756 $messages = 0;
757 $totalSize = 0;
759 if (is_array($this->quota)) {
760 $quota = $this->quota;
761 } else {
762 try {
763 $quota = $this->getQuota(true);
764 } catch (StorageException\ExceptionInterface $e) {
765 throw new StorageException\RuntimeException('no quota definition found', 0, $e);
769 $folders = new RecursiveIteratorIterator($this->getFolders(), RecursiveIteratorIterator::SELF_FIRST);
770 foreach ($folders as $folder) {
771 $subdir = $folder->getGlobalName();
772 if ($subdir == 'INBOX') {
773 $subdir = '';
774 } else {
775 $subdir = '.' . $subdir;
777 if ($subdir == 'Trash') {
778 continue;
781 foreach (['cur', 'new'] as $subsubdir) {
782 $dirname = $this->rootdir . $subdir . DIRECTORY_SEPARATOR . $subsubdir . DIRECTORY_SEPARATOR;
783 if (! file_exists($dirname)) {
784 continue;
786 // NOTE: we are using mtime instead of "the latest timestamp". The latest would be atime
787 // and as we are accessing the directory it would make the whole calculation useless.
788 $timestamps[$dirname] = filemtime($dirname);
790 $dh = opendir($dirname);
791 // NOTE: Should have been checked in constructor. Not throwing an exception here, quotas will
792 // therefore not be fully enforced, but next request will fail anyway, if problem persists.
793 if (! $dh) {
794 continue;
797 while (($entry = readdir()) !== false) {
798 if ($entry[0] == '.' || ! is_file($dirname . $entry)) {
799 continue;
802 if (strpos($entry, ',S=')) {
803 strtok($entry, '=');
804 $filesize = strtok(':');
805 if (is_numeric($filesize)) {
806 $totalSize += $filesize;
807 ++$messages;
808 continue;
811 $size = filesize($dirname . $entry);
812 if ($size === false) {
813 // ignore, as we assume file got removed
814 continue;
816 $totalSize += $size;
817 ++$messages;
822 $tmp = $this->createTmpFile();
823 $fh = $tmp['handle'];
824 $definition = [];
825 foreach ($quota as $type => $value) {
826 if ($type == 'size' || $type == 'count') {
827 $type = $type == 'count' ? 'C' : 'S';
829 $definition[] = $value . $type;
831 $definition = implode(',', $definition);
832 fwrite($fh, "$definition\n");
833 fwrite($fh, "$totalSize $messages\n");
834 fclose($fh);
835 rename($tmp['filename'], $this->rootdir . 'maildirsize');
836 foreach ($timestamps as $dir => $timestamp) {
837 if ($timestamp < filemtime($dir)) {
838 unlink($this->rootdir . 'maildirsize');
839 break;
843 return ['size' => $totalSize,
844 'count' => $messages,
845 'quota' => $quota];
849 * @see http://www.inter7.com/courierimap/README.maildirquota.html "Calculating the quota for a Maildir++"
850 * @param bool $forceRecalc
851 * @return array
853 protected function calculateQuota($forceRecalc = false)
855 $fh = null;
856 $totalSize = 0;
857 $messages = 0;
858 $maildirsize = '';
859 if (! $forceRecalc
860 && file_exists($this->rootdir . 'maildirsize')
861 && filesize($this->rootdir . 'maildirsize') < 5120
863 $fh = fopen($this->rootdir . 'maildirsize', 'r');
865 if ($fh) {
866 $maildirsize = fread($fh, 5120);
867 if (strlen($maildirsize) >= 5120) {
868 fclose($fh);
869 $fh = null;
870 $maildirsize = '';
873 if (! $fh) {
874 $result = $this->calculateMaildirsize();
875 $totalSize = $result['size'];
876 $messages = $result['count'];
877 $quota = $result['quota'];
878 } else {
879 $maildirsize = explode("\n", $maildirsize);
880 if (is_array($this->quota)) {
881 $quota = $this->quota;
882 } else {
883 $definition = explode(',', $maildirsize[0]);
884 $quota = [];
885 foreach ($definition as $member) {
886 $key = $member[strlen($member) - 1];
887 if ($key == 'S' || $key == 'C') {
888 $key = $key == 'C' ? 'count' : 'size';
890 $quota[$key] = substr($member, 0, -1);
893 unset($maildirsize[0]);
894 foreach ($maildirsize as $line) {
895 list($size, $count) = explode(' ', trim($line));
896 $totalSize += $size;
897 $messages += $count;
901 $overQuota = false;
902 $overQuota = $overQuota || (isset($quota['size']) && $totalSize > $quota['size']);
903 $overQuota = $overQuota || (isset($quota['count']) && $messages > $quota['count']);
904 // NOTE: $maildirsize equals false if it wasn't set (AKA we recalculated) or it's only
905 // one line, because $maildirsize[0] gets unsetted.
906 // Also we're using local time to calculate the 15 minute offset. Touching a file just for known the
907 // local time of the file storage isn't worth the hassle.
908 if ($overQuota && ($maildirsize || filemtime($this->rootdir . 'maildirsize') > time() - 900)) {
909 $result = $this->calculateMaildirsize();
910 $totalSize = $result['size'];
911 $messages = $result['count'];
912 $quota = $result['quota'];
913 $overQuota = false;
914 $overQuota = $overQuota || (isset($quota['size']) && $totalSize > $quota['size']);
915 $overQuota = $overQuota || (isset($quota['count']) && $messages > $quota['count']);
918 if ($fh) {
919 // TODO is there a safe way to keep the handle open for writing?
920 fclose($fh);
923 return ['size' => $totalSize,
924 'count' => $messages,
925 'quota' => $quota,
926 'over_quota' => $overQuota];
929 protected function addQuotaEntry($size, $count = 1)
931 if (! file_exists($this->rootdir . 'maildirsize')) {
932 // TODO: should get file handler from calculateQuota
934 $size = (int) $size;
935 $count = (int) $count;
936 file_put_contents($this->rootdir . 'maildirsize', "$size $count\n", FILE_APPEND);
940 * check if storage is currently over quota
942 * @see calculateQuota()
943 * @param bool $detailedResponse return known data of quota and current size and message count
944 * @param bool $forceRecalc
945 * @return bool|array over quota state or detailed response
947 public function checkQuota($detailedResponse = false, $forceRecalc = false)
949 $result = $this->calculateQuota($forceRecalc);
950 return $detailedResponse ? $result : $result['over_quota'];