Adapts broken addresses processing to new mail chain.
[platal.git] / include / emails.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 define('SUCCESS', 1);
23 define('ERROR_INACTIVE_REDIRECTION', 2);
24 define('ERROR_INVALID_EMAIL', 3);
25 define('ERROR_LOOP_EMAIL', 4);
26
27 // function mark_broken_email() {{{1
28 function mark_broken_email($email, $admin = false)
29 {
30 $email = valide_email($email);
31 if (empty($email) || $email == '@') {
32 return;
33 }
34
35 $user = XDB::fetchOneAssoc('SELECT r1.uid, r1.broken_level != 0 AS broken, a.hruid, COUNT(r2.uid) AS nb_mails, a.full_name, s.email AS alias
36 FROM email_redirect_account AS r1
37 INNER JOIN accounts AS a ON (a.uid = r1.uid)
38 INNER JOIN email_source_account AS s ON (a.uid = s.uid AND s.flags = \'bestalias\')
39 LEFT JOIN email_redirect_account AS r2 ON (a.uid = r2.uid AND r1.redirect != r2.redirect AND
40 r2.broken_level = 0 AND r2.flags = \'active\' AND
41 (r2.type = \'smtp\' OR r2.type = \'googleapps\'))
42 WHERE r1.redirect = {?}
43 GROUP BY r1.uid', $email);
44
45 if ($user) {
46 // Mark address as broken.
47 if (!$user['broken']) {
48 XDB::execute('UPDATE email_redirect_account
49 SET broken_date = NOW(), last = NOW(), broken_level = 1
50 WHERE redirect = {?}', $email);
51 } elseif ($admin) {
52 XDB::execute('UPDATE email_redirect_account
53 SET last = CURDATE(), broken_level = IF(broken_level > 1, 3, 2)
54 WHERE redirect = {?} AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
55 $email);
56 } else {
57 XDB::execute('UPDATE email_redirect_account
58 SET broken_level = 1
59 WHERE redirect = {?} AND broken_level = 0', $email);
60 }
61 }
62
63 return $user;
64 }
65
66 // function fix_bestalias() {{{1
67 // Checks for an existing 'bestalias' among the the current user's aliases, and
68 // eventually selects a new bestalias when required.
69 function fix_bestalias(User $user)
70 {
71 $count = XDB::fetchOneCell('SELECT COUNT(*)
72 FROM email_source_account
73 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags)',
74 $user->id());
75
76 if ($count == 1) {
77 return;
78 } elseif ($count > 1) {
79 // If too many bestaliases, delete the bestalias flag from all this
80 // user's emails (this should never happen).
81 XDB::execute("UPDATE email_source_account
82 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
83 WHERE uid = {?}",
84 $user->id());
85 }
86
87 // If no bestalias is selected, we choose the shortest email which is not
88 // related to a usage name and contains a '.'.
89 XDB::execute("UPDATE email_source_account
90 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
91 WHERE uid = {?}
92 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
93 LIMIT 1",
94 $user->id());
95 }
96
97 // function valide_email() {{{1
98 // Returns a cleaned-up version of the @p email string. It removes garbage
99 // characters, and determines the canonical form (without _ and +) for
100 // Polytechnique.org email addresses.
101 function valide_email($str)
102 {
103 global $globals;
104
105 $em = trim(rtrim($str));
106 $em = str_replace('<', '', $em);
107 $em = str_replace('>', '', $em);
108 if (strpos($em, '@') === false) {
109 return;
110 }
111 list($ident, $dom) = explode('@', $em);
112 if ($dom == $globals->mail->domain || $dom == $globals->mail->domain2) {
113 list($ident1) = explode('_', $ident);
114 list($ident) = explode('+', $ident1);
115 }
116 return $ident . '@' . $dom;
117 }
118
119 // function isvalid_email_redirection() {{{1
120 /** Checks if an email is a suitable redirection.
121 * @param $email the email to check
122 * @return BOOL
123 */
124 function isvalid_email_redirection($email)
125 {
126 return isvalid_email($email) &&
127 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
128 }
129
130 // function ids_from_mails() {{{1
131 // Converts an array of emails to an array of email => uid, where email is the
132 // given email when we found a matching user.
133 function ids_from_mails(array $emails)
134 {
135 global $globals;
136
137 // Removes duplicates, if any.
138 $emails = array_unique($emails);
139
140 // Formats and splits by domain type (locally managed or external) emails.
141 $domain_emails = array();
142 $other_emails = array();
143 foreach ($emails as $email) {
144 if (strpos($email, '@') === false) {
145 $user = $email;
146 $domain = $globals->mail->domain2;
147 } else {
148 list($user, $domain) = explode('@', $email);
149 }
150 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2
151 || $domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
152 list($user) = explode('+', $user);
153 list($user) = explode('_', $user);
154 $domain_emails[$email] = strtolower($user . '@' . $domain);
155 } else {
156 $other_emails[$email] = strtolower($user . '@' . $domain);
157 }
158 }
159
160 // Retrieves emails from our domains.
161 $domain_uids = XDB::fetchAllAssoc('email',
162 'SELECT email, uid
163 FROM email_source_account
164 WHERE email IN {?}',
165 array_unique($domain_emails));
166
167 // Retrieves emails from redirections.
168 $other_uids = XDB::fetchAllAssoc('redirect',
169 'SELECT redirect, uid
170 FROM email_redirect_account
171 WHERE redirect IN {?}',
172 array_unique($other_emails));
173
174 // Associates given emails with the corresponding uid.
175 $uids = array();
176 foreach (array_merge($domain_emails, $other_emails) as $email => $canonical_email) {
177 if (array_key_exists($canonical_email, $domain_uids)) {
178 $uids[$email] = $domain_uids[$canonical_email];
179 } elseif (array_key_exists($canonical_email, $other_uids)) {
180 $uids[$email] = $other_uids[$canonical_email];
181 }
182 }
183
184 return $uids;
185 }
186
187 // class Bogo {{{1
188 // The Bogo class represents a spam filtering level in plat/al architecture.
189 class Bogo
190 {
191 private static $states = array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
192
193 private $user;
194 private $state;
195
196 public function __construct(User $user)
197 {
198 if (!$user) {
199 return;
200 }
201
202 $this->user = &$user;
203 $res = XDB::query('SELECT action
204 FROM email_redirect_account
205 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
206 $user->id());
207 if ($res->numRows() == 0) {
208 return;
209 }
210 $this->state = $res->fetchOneCell();
211 }
212
213 public function change($state)
214 {
215 $this->state = is_int($state) ? self::$states[$state] : $state;
216 XDB::execute('UPDATE email_redirect_account
217 SET action = {?}
218 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
219 $this->state, $this->user->id());
220 }
221
222 public function level()
223 {
224 return array_search($this->state, self::$states);
225 }
226 }
227
228 // class Email {{{1
229 // Represents an "email address" used as final recipient for plat/al-managed
230 // addresses.
231 class Email
232 {
233 // Lists fields to load automatically.
234 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
235
236 // Shortname to realname mapping for known mail storage backends.
237 static private $display_names = array(
238 'imap' => 'Accès de secours aux emails (IMAP)',
239 'googleapps' => 'Compte Google Apps',
240 );
241 static private $storage_domains = array(
242 'imap' => 'imap',
243 'googleapps' => 'g'
244 );
245
246 private $user;
247
248 // Basic email properties; $sufficient indicates if the email can be used as
249 // an unique redirection; $redirect contains the delivery email address.
250 public $type;
251 public $sufficient;
252 public $email;
253 public $display_email;
254 public $domain;
255 public $action;
256
257 // Redirection status properties.
258 public $active;
259 public $inactive;
260 public $broken;
261 public $disabled;
262 public $rewrite;
263 public $allow_rewrite;
264 public $hash;
265
266 // Redirection bounces stats.
267 public $last;
268 public $broken_level;
269 public $broken_date;
270
271 public function __construct(User $user, array $row)
272 {
273 foreach (self::$field_names as $field) {
274 if (array_key_exists($field, $row)) {
275 $this->$field = $row[$field];
276 }
277 }
278 $this->email = $row['redirect'];
279
280 if (array_key_exists($this->type, Email::$display_names)) {
281 $this->display_email = self::$display_names[$this->type];
282 } else {
283 $this->display_email = $this->email;
284 }
285 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
286 $this->$status = ($status == $row['flags']);
287 }
288 $this->sufficient = ($this->type == 'smtp' || $this->type == 'googleapps');
289 $this->user = &$user;
290 }
291
292 // Activates the email address as a redirection.
293 public function activate()
294 {
295 if ($this->inactive) {
296 XDB::execute('UPDATE email_redirect_account
297 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
298 WHERE uid = {?} AND redirect = {?}',
299 $this->user->id(), $this->email);
300 S::logger()->log('email_on', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ''));
301 $this->inactive = false;
302 $this->active = true;
303 }
304 }
305
306 // Deactivates the email address as a redirection.
307 public function deactivate()
308 {
309 if ($this->active) {
310 XDB::execute('UPDATE email_redirect_account
311 SET flags = \'inactive\'
312 WHERE uid = {?} AND redirect = {?}',
313 $this->user->id(), $this->email);
314 S::logger()->log('email_off', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
315 $this->inactive = true;
316 $this->active = false;
317 }
318 }
319
320
321 // Sets the rewrite rule for the given address.
322 public function set_rewrite($rewrite)
323 {
324 if ($this->type != 'smtp' || $this->rewrite == $rewrite) {
325 return;
326 }
327 if (!$rewrite || !isvalid_email($rewrite)) {
328 $rewrite = '';
329 }
330 XDB::execute('UPDATE email_redirect_account
331 SET rewrite = {?}
332 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
333 $rewrite, $this->user->id(), $this->email);
334 $this->rewrite = $rewrite;
335 if (!$this->allow_rewrite) {
336 global $globals;
337 if (empty($this->hash)) {
338 $this->hash = rand_url_id();
339 XDB::execute('UPDATE email_redirect_account
340 SET hash = {?}
341 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
342 $this->hash, $this->user->id(), $this->email);
343 }
344 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
345 $mail->assign('mail', $this);
346 $mail->assign('user', $this->user);
347 $mail->assign('baseurl', $globals->baseurl);
348 $mail->assign('sitename', $globals->core->sitename);
349 $mail->assign('to', $this->email);
350 $mail->send($this->user->isEmailFormatHtml());
351 }
352 }
353
354
355 // Resets the error counts associated with the redirection.
356 public function clean_errors()
357 {
358 if ($this->type != 'smtp') {
359 return;
360 }
361 if (!S::admin()) {
362 return false;
363 }
364 $this->broken = 0;
365 $this->broken_level = 0;
366 $this->last = 0;
367 return XDB::execute('UPDATE email_redirect_account
368 SET broken_level = 0, broken_date = 0, last = 0
369 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
370 $this->user->id(), $this->email);
371 }
372
373
374 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
375 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
376 // can be definitively removed; 'disable' indicates if the email has a third
377 // status 'disabled' in addition to 'active' and 'inactive').
378 public function has_rewrite()
379 {
380 return ($this->type == 'smtp');
381 }
382
383 public function is_removable()
384 {
385 return ($this->type == 'smtp');
386 }
387
388 public function has_disable()
389 {
390 return true;
391 }
392
393 public function is_redirection()
394 {
395 return ($this->type == 'smtp');
396 }
397
398 // Returns the list of allowed storages for the @p user.
399 static private function get_allowed_storages(User $user)
400 {
401 global $globals;
402 $storages = array();
403
404 // Google Apps storage is available for users with valid Google Apps account.
405 require_once 'googleapps.inc.php';
406 if ($globals->mailstorage->googleapps_domain &&
407 GoogleAppsAccount::account_status($user->id()) == 'active') {
408 $storages[] = 'googleapps';
409 }
410
411 // IMAP storage is always visible to administrators, and is allowed for
412 // everyone when the service is marked as 'active'.
413 if ($globals->mailstorage->imap_active || S::admin()) {
414 $storages[] = 'imap';
415 }
416
417 return $storages;
418 }
419
420 static public function activate_storage(User $user, $storage)
421 {
422 Platal::assert(in_array($storage, self::get_allowed_storages($user)));
423
424 if (!self::is_active_storage($user, $storage)) {
425 global $globals;
426
427 XDB::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
428 VALUES ({?}, {?}, {?}, \'active\')',
429 $user->id(), $storage,
430 $user->hruid . '@' . self::$storage_domains[$storage] . '.' . $globals->mail->domain);
431 }
432 }
433
434 static public function deactivate_storage(User $user, $storage)
435 {
436 if (in_array($storage, self::$storage_domains)) {
437 XDB::execute('DELETE FROM email_redirect_account
438 WHERE uid = {?} AND type = {?}',
439 $user->id(), $storage);
440 }
441 }
442
443 static public function is_active_storage(User $user, $storage)
444 {
445 if (!in_array($storage, self::$storage_domains)) {
446 return false;
447 }
448 $res = XDB::fetchOneCell('SELECT COUNT(*)
449 FROM email_redirect_account
450 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
451 $user->id(), $storage);
452 return !is_null($res) && $res > 0;
453 }
454 }
455 // class Redirect {{{1
456 // Redirect is a placeholder class for an user's active redirections (third-party
457 // redirection email, or Polytechnique.org mail storages).
458 class Redirect
459 {
460 private $flags = 'active';
461 private $user;
462
463 public $emails;
464 public $bogo;
465
466 public function __construct(User $user)
467 {
468 $this->user = &$user;
469 $this->bogo = new Bogo($user);
470
471 // Adds third-party email redirections.
472 $res = XDB::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
473 FROM email_redirect_account
474 WHERE uid = {?} AND type != \'homonym\'',
475 $user->id());
476 $this->emails = array();
477 while ($row = $res->next()) {
478 $this->emails[] = new Email($user, $row);
479 }
480 }
481
482 public function other_active($email)
483 {
484 foreach ($this->emails as $mail) {
485 if ($mail->email != $email && $mail->active && $mail->sufficient) {
486 return true;
487 }
488 }
489 return false;
490 }
491
492 public function delete_email($email)
493 {
494 if (!$this->other_active($email)) {
495 return ERROR_INACTIVE_REDIRECTION;
496 }
497 XDB::execute('DELETE FROM email_redirect_account
498 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
499 $this->user->id(), $email);
500 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
501 foreach ($this->emails as $i => $mail) {
502 if ($email == $mail->email) {
503 unset($this->emails[$i]);
504 }
505 }
506 check_redirect($this);
507 return SUCCESS;
508 }
509
510 public function add_email($email)
511 {
512 $email_stripped = strtolower(trim($email));
513 if (!isvalid_email($email_stripped)) {
514 return ERROR_INVALID_EMAIL;
515 }
516 if (!isvalid_email_redirection($email_stripped)) {
517 return ERROR_LOOP_EMAIL;
518 }
519 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
520 XDB::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
521 VALUES ({?}, {?}, \'active\')',
522 $this->user->id(), $email);
523 if ($logger = S::v('log', null)) { // may be absent --> step4.php
524 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
525 }
526 foreach ($this->emails as $mail) {
527 if ($mail->email == $email_stripped) {
528 return SUCCESS;
529 }
530 }
531 $this->emails[] = new Email($this->user, array(
532 'redirect' => $email,
533 'rewrite' => '',
534 'type' => 'smtp',
535 'action' => 'default',
536 'broken_date' => '0000-00-00',
537 'broken_level' => 0,
538 'last' => '0000-00-00',
539 'flags' => 'active',
540 'hash' => null,
541 'allow_rewrite' => 0
542 ));
543
544 // security stuff
545 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
546 check_redirect($this);
547 return SUCCESS;
548 }
549
550 public function modify_email($emails_actifs, $emails_rewrite)
551 {
552 foreach ($this->emails as &$email) {
553 if (in_array($email->email, $emails_actifs)) {
554 $email->activate();
555 } else {
556 $email->deactivate();
557 }
558 $email->set_rewrite($emails_rewrite[$email->email]);
559 }
560 check_redirect($this);
561 return SUCCESS;
562 }
563
564 public function modify_one_email($email, $activate)
565 {
566 $allinactive = true;
567 $thisone = false;
568 foreach ($this->emails as $i=>$mail) {
569 if ($mail->email == $email) {
570 $thisone = $i;
571 }
572 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
573 }
574 if ($thisone === false) {
575 return ERROR_INVALID_EMAIL;
576 }
577 if ($allinactive || $activate) {
578 $this->emails[$thisone]->activate();
579 } else {
580 $this->emails[$thisone]->deactivate();
581 }
582 check_redirect($this);
583 if ($allinactive && !$activate) {
584 return ERROR_INACTIVE_REDIRECTION;
585 }
586 return SUCCESS;
587 }
588
589 public function modify_one_email_redirect($email, $redirect)
590 {
591 foreach ($this->emails as &$mail) {
592 if ($mail->email == $email) {
593 $mail->set_rewrite($redirect);
594 check_redirect($this);
595 return;
596 }
597 }
598 }
599
600 public function clean_errors($email)
601 {
602 foreach ($this->emails as &$mail) {
603 if ($mail->email == $email) {
604 check_redirect($this);
605 return $mail->clean_errors();
606 }
607 }
608 return false;
609 }
610
611 public function disable()
612 {
613 XDB::execute("UPDATE email_redirect_account
614 SET flags = 'disable'
615 WHERE flags = 'active' AND uid = {?}", $this->user->id());
616 foreach ($this->emails as &$mail) {
617 if ($mail->active && $mail->has_disable()) {
618 $mail->disabled = true;
619 $mail->active = false;
620 }
621 }
622 check_redirect($this);
623 }
624
625 public function enable()
626 {
627 XDB::execute("UPDATE email_redirect_account
628 SET flags = 'active'
629 WHERE flags = 'disable' AND uid = {?}", $this->user->id());
630 foreach ($this->emails as &$mail) {
631 if ($mail->disabled) {
632 $mail->disabled = false;
633 $mail->active = true;
634 }
635 check_redirect($this);
636 }
637 }
638
639 public function get_broken_mx()
640 {
641 $res = XDB::query("SELECT host, text
642 FROM mx_watch
643 WHERE state != 'ok'");
644 if (!$res->numRows()) {
645 return array();
646 }
647 $mxs = $res->fetchAllAssoc();
648 $mails = array();
649 foreach ($this->emails as &$mail) {
650 if ($mail->active && strstr($mail->email, '@') !== false) {
651 list(,$domain) = explode('@', $mail->email);
652 getmxrr($domain, $lcl_mxs);
653 if (empty($lcl_mxs)) {
654 $lcl_mxs = array($domain);
655 }
656 $broken = false;
657 foreach ($mxs as &$mx) {
658 foreach ($lcl_mxs as $lcl) {
659 if (fnmatch($mx['host'], $lcl)) {
660 $broken = $mx['text'];
661 break;
662 }
663 }
664 if ($broken) {
665 $mails[] = array('mail' => $mail->email, 'text' => $broken);
666 break;
667 }
668 }
669 }
670 }
671 return $mails;
672 }
673
674 public function active_emails()
675 {
676 $emails = array();
677 foreach ($this->emails as $mail) {
678 if ($mail->active) {
679 $emails[] = $mail;
680 }
681 }
682 return $emails;
683 }
684
685 public function get_uid()
686 {
687 return $this->user->id();
688 }
689 }
690
691 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
692 ?>