Debian Codegraph @

classes/Mail/PhpExtension/MailBox.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2020-2024 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 namespace Liuch\DmarcSrg\Mail\PhpExtension;
24
25 use Liuch\DmarcSrg\Core;
26 use Liuch\DmarcSrg\ErrorHandler;
27 use Liuch\DmarcSrg\Exception\SoftException;
28 use Liuch\DmarcSrg\Exception\LogicException;
29 use Liuch\DmarcSrg\Exception\MailboxException;
30
31 class MailBox extends \Liuch\DmarcSrg\Mail\MailBox
32 {
33 private $conn;
34 private $server;
35 private $delim;
36 private $attrs;
37 private $options;
38
39 public function __construct(array $params)
40 {
41 parent::__construct($params);
42 $this->conn = null;
43
44 switch ($this->encrypt) {
45 case 'ssl':
46 default:
47 $flags = '/ssl';
48 break;
49 case 'none':
50 $flags = '/notls';
51 break;
52 case 'starttls':
53 $flags = '/tls';
54 break;
55 }
56 if ($this->nocert) {
57 $flags .= '/novalidate-cert';
58 }
59
60 $this->server = sprintf('{%s/imap%s}', $this->host, $flags);
61 $this->options = [];
62
63 if (isset($params['auth_exclude'])) {
64 $auth_exclude = $params['auth_exclude'];
65 switch (gettype($auth_exclude)) {
66 case 'string':
67 $auth_exclude = [ $auth_exclude ];
68 break;
69 case 'array':
70 break;
71 default:
72 $auth_exclude = null;
73 break;
74 }
75 if ($auth_exclude) {
76 $this->options['DISABLE_AUTHENTICATOR'] = $auth_exclude;
77 }
78 }
79 }
80
81 public function __clone(): void
82 {
83 parent::__clone();
84 $this->conn = null;
85 }
86
87 /**
88 * Deletes messages marked for deletion
89 *
90 * @return void
91 */
92 public function expunge(): void
93 {
94 if (extension_loaded('imap')) {
95 self::resetErrorStack();
96 try {
97 imap_expunge($this->conn);
98 } catch (\ErrorException $e) {
99 }
100 $this->logImapError('imap_expunge');
101 }
102 }
103
104 /**
105 * Deletes messages marked for deletion, if any, and closes the connection
106 *
107 * @return void
108 */
109 public function cleanup(): void
110 {
111 if (extension_loaded('imap')) {
112 self::resetErrorStack();
113 if (!is_null($this->conn)) {
114 try {
115 imap_close($this->conn);
116 $this->conn = null;
117 } catch (\ErrorException $e) {
118 }
119 $this->logImapError('imap_close');
120 }
121 }
122 }
123
124 /**
125 * Returns the underlying connection
126 *
127 * @return \IMAP\Connection
128 */
129 public function connection()
130 {
131 $this->ensureConnection();
132 return $this->conn;
133 }
134
135 public function connect(): void
136 {
137 $this->ensureConnection();
138 }
139
140 public function delimiter(): string
141 {
142 if (!$this->delim) {
143 $this->ensureConnection();
144 }
145 return $this->delim;
146 }
147
148 public function childMailbox(string $folder)
149 {
150 $this->ensureConnection();
151 try {
152 $mb_list = imap_list(
153 $this->conn,
154 self::utf8ToMutf7($this->server),
155 self::utf8ToMutf7($this->mbox) . $this->delim . self::utf8ToMutf7($folder)
156 );
157 } catch (\ErrorException $e) {
158 $mb_list = false;
159 }
160 $this->logImapError('imap_list');
161 if (!$mb_list) {
162 return null;
163 }
164 $child = clone $this;
165 $child->mbox .= $this->delim . $folder;
166 return $child;
167 }
168
169 public function check(): array
170 {
171 try {
172 $this->ensureConnection();
173 try {
174 $res = imap_status(
175 $this->conn,
176 self::utf8ToMutf7($this->server . $this->mbox),
177 SA_MESSAGES | SA_UNSEEN
178 );
179 } catch (\ErrorException $e) {
180 $res = false;
181 }
182 $error_message = $this->logImapError();
183 if (!$res) {
184 throw new MailboxException($error_message ?? 'Failed to get the mail box status');
185 }
186
187 if ($this->attrs & \LATT_NOSELECT) {
188 throw new MailboxException('The resource is not a mailbox');
189 }
190
191 $this->checkRights();
192 } catch (MailboxException $e) {
193 return ErrorHandler::exceptionResult($e);
194 }
195 return [
196 'error_code' => 0,
197 'message' => 'Successfully',
198 'status' => [
199 'messages' => $res->messages,
200 'unseen' => $res->unseen
201 ]
202 ];
203 }
204
205 public function messages(int $search_criteria, int $sort_criteria): array
206 {
207 $this->ensureConnection();
208
209 switch ($search_criteria) {
210 case static::SEARCH_ALL:
211 $search = 'ALL';
212 break;
213 case static::SEARCH_SEEN:
214 $search = 'SEEN';
215 break;
216 case static::SEARCH_UNSEEN:
217 $search = 'UNSEEN';
218 break;
219 default:
220 throw new LogicException('imap_sort: Incorrect search criteria');
221 }
222 switch ($sort_criteria) {
223 case static::ORDER_ASCENT:
224 $reverse = 0;
225 break;
226 case static::ORDER_DESCENT:
227 $reverse = 1;
228 break;
229 default:
230 throw new LogicException('imap_sort: Incorrect sort criteria');
231 }
232 try {
233 $res = imap_sort($this->conn, SORTDATE, $reverse, SE_NOPREFETCH | SE_UID, $search);
234 } catch (\ErrorException $e) {
235 $res = false;
236 }
237 $error_message = $this->logImapError('imap_sort');
238 if ($res === false) {
239 if ($error_message) {
240 throw new MailboxException('Failed to sort email messages', -1, new \ErrorException($error_message));
241 }
242 $res = [];
243 }
244 return array_map(function ($number) {
245 return new MailMessage([ 'mailbox' => $this, 'number' => $number ]);
246 }, $res);
247 }
248
249 public function ensureMailbox($folder): void
250 {
251 $mbn = self::utf8ToMutf7($folder);
252 $srv = self::utf8ToMutf7($this->server);
253 $mbo = self::utf8ToMutf7($this->mbox);
254 $this->ensureConnection();
255 try {
256 $mb_list = imap_list($this->conn, $srv, $mbo . $this->delim . $mbn);
257 } catch (\ErrorException $e) {
258 $mb_list = false;
259 }
260 $error_message = $this->logImapError('imap_list');
261 if (empty($mb_list)) {
262 if ($error_message) {
263 throw new MailboxException(
264 'Failed to get the list of mailboxes',
265 -1,
266 new \ErrorException($error_message)
267 );
268 }
269
270 $new_mailbox = "{$srv}{$mbo}{$this->delim}{$mbn}";
271 try {
272 $res = imap_createmailbox($this->conn, $new_mailbox);
273 } catch (\ErrorException $e) {
274 $res = false;
275 }
276 $error_message = $this->logImapError('imap_createmailbox');
277 if (!$res) {
278 throw new MailboxException(
279 'Failed to create a new mailbox',
280 -1,
281 new \ErrorException($error_message ?? 'Unknown')
282 );
283 }
284
285 try {
286 imap_subscribe($this->conn, $new_mailbox);
287 } catch (\ErrorException $e) {
288 }
289 $this->logImapError('imap_subscribe');
290 }
291 }
292
293 public static function resetErrorStack()
294 {
295 imap_errors();
296 imap_alerts();
297 }
298
299 /**
300 * It's a replacement for the standard function imap_utf8_to_mutf7
301 *
302 * @param string $s A UTF-8 encoded string
303 *
304 * @return string|false
305 */
306 public static function utf8ToMutf7(string $s)
307 {
308 return mb_convert_encoding($s, 'UTF7-IMAP', 'UTF-8');
309 }
310
311 private function ensureConnection()
312 {
313 if (is_null($this->conn)) {
314 if (isset($this->authm) && $this->authm !== 'plain') {
315 throw new LogicException('Unknown authentication method');
316 }
317 $error_message = null;
318 $srv = self::utf8ToMutf7($this->server);
319 try {
320 $this->conn = imap_open(
321 $srv,
322 $this->uname,
323 $this->passw,
324 OP_HALFOPEN,
325 0,
326 $this->options
327 );
328 } catch (\ErrorException $e) {
329 $this->conn = null;
330 }
331 if ($this->conn) {
332 $mbx = self::utf8ToMutf7($this->mbox);
333 try {
334 $mb_list = imap_getmailboxes($this->conn, $srv, $mbx);
335 } catch (\ErrorException $e) {
336 $mb_list = null;
337 }
338 if ($mb_list && count($mb_list) === 1) {
339 $this->delim = $mb_list[0]->delimiter ?? '/';
340 $this->attrs = $mb_list[0]->attributes ?? 0;
341 try {
342 if (imap_reopen($this->conn, $srv . $mbx)) {
343 return;
344 }
345 } catch (\ErrorException $e) {
346 }
347 } else {
348 $error_message = "Mailbox `{$this->mbox}` not found";
349 }
350 }
351 if (!$error_message) {
352 $error_message = imap_last_error();
353 if (!$error_message) {
354 $error_message = 'Cannot connect to the mail server';
355 }
356 }
357 Core::instance()->logger()->error("IMAP error: {$error_message}");
358 self::resetErrorStack();
359 if ($this->conn) {
360 try {
361 imap_close($this->conn);
362 } catch (\ErrorException $e) {
363 }
364 $this->logImapError('imap_close');
365 }
366 $this->conn = null;
367 throw new MailboxException($error_message);
368 }
369 }
370
371 /**
372 * Extracts and logs IMAP errors if any
373 *
374 * @param string $prefix Prefix for the log entry line
375 *
376 * @return string|null Error string
377 */
378 public function logImapError(string $prefix = 'IMAP error')
379 {
380 if ($error_message = imap_last_error()) {
381 self::resetErrorStack();
382 $error_message = "{$prefix}: {$error_message}";
383 Core::instance()->logger()->error($error_message);
384 return $error_message;
385 }
386 return null;
387 }
388
389 private function checkRights(): void
390 {
391 if ($this->attrs & \LATT_NOINFERIORS) {
392 throw new SoftException('The mailbox may not have any children mailboxes');
393 }
394
395 if (!function_exists('imap_getacl')) {
396 return;
397 }
398
399 $mbox = self::utf8ToMutf7($this->mbox);
400 try {
401 $acls = imap_getacl($this->conn, $mbox);
402 } catch (\ErrorException $e) {
403 // It's not possible to get the ACLs information
404 $acls = false;
405 }
406 $this->logImapError('imap_getacl');
407 if ($acls !== false) {
408 $needed_rights_map = [
409 'l' => 'LOOKUP',
410 'r' => 'READ',
411 's' => 'WRITE-SEEN',
412 't' => 'WRITE-DELETE',
413 'k' => 'CREATE'
414 ];
415 $result = [];
416 $needed_rights = array_keys($needed_rights_map);
417 foreach ([ "#{$this->uname}", '#authenticated', '#anyone' ] as $identifier) {
418 if (isset($acls[$identifier])) {
419 $rights = $acls[$identifier];
420 foreach ($needed_rights as $r) {
421 if (!str_contains($rights, $r)) {
422 $result[] = $needed_rights_map[$r];
423 }
424 }
425 break;
426 }
427 }
428 if (count($result) > 0) {
429 throw new SoftException(
430 'Not enough rights. Additionally, these rights are required: ' . implode(', ', $result)
431 );
432 }
433 }
434 }
435 }