Implements best_domain (Closes #1404).
[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 add_to_list_alias(User $user, $local_part, $domain, $type = 'alias')
28 {
29 Platal::assert($user !== null);
30
31 XDB::execute('INSERT IGNORE INTO email_virtual (email, domain, redirect, type)
32 SELECT {?}, id, {?}, {?}
33 FROM email_virtual_domains
34 WHERE name = {?}',
35 $local_part, $user->forlifeEmail(), $type, $domain);
36 }
37
38 function delete_from_list_alias(User $user, $local_part, $domain, $type = 'alias')
39 {
40 Platal::assert($user !== null);
41
42 XDB::execute('DELETE v
43 FROM email_virtual AS v
44 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
45 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
46 WHERE v.email = {?} AND d.name = {?} AND v.redirect = {?} AND type = {?}',
47 $local_part, $domain, $user->forlifeEmail(), $type);
48 }
49
50 function update_list_alias(User $user, $former_email, $local_part, $domain, $type = 'alias')
51 {
52 Platal::assert($user !== null);
53
54 XDB::execute('UPDATE email_virtual AS v
55 INNER JOIN email_virtual_domains AS d ON (v.domain = d.id)
56 SET v.redirect = {?}
57 WHERE v.redirect = {?} AND d.name = {?} AND v.email = {?} AND v.type = {?}',
58 $user->forlifeEmail(), $former_email, $domain, $local_part, $type);
59 }
60
61 function list_alias_members($local_part, $domain)
62 {
63 $emails = XDB::fetchColumn('SELECT DISTINCT(redirect)
64 FROM email_virtual AS v
65 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
66 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
67 WHERE v.email = {?} AND d.name = {?} AND type = \'alias\'',
68 $local_part, $domain);
69
70 $members = array();
71 foreach ($emails as $email) {
72 $members[] = User::getSilent($email);
73 }
74
75 return $members;
76 }
77
78 function delete_list_alias($local_part, $domain)
79 {
80 XDB::execute('DELETE v
81 FROM email_virtual AS v
82 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
83 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
84 WHERE v.email = {?} AND d.name = {?} AND type = \'alias\'',
85 $local_part, $domain);
86 }
87
88 function iterate_list_alias($domain)
89 {
90 return XDB::fetchColumn('SELECT CONCAT(v.email, \'@\', m.name)
91 FROM email_virtual AS v
92 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
93 WHERE m.name = {?} AND v.type = \'alias\'
94 GROUP BY v.email',
95 $domain);
96 }
97
98 function create_list($local_part, $domain)
99 {
100 global $globals;
101
102 $redirect = $domain . '_' . $local_part . '+';
103 foreach(array('post', 'owner', 'admin', 'bounces', 'unsubscribe') as $suffix) {
104 XDB::execute('INSERT IGNORE INTO email_virtual (email, domain, redirect, type)
105 SELECT {?}, id, {?}, \'list\'
106 FROM email_virtual_domains
107 WHERE name = {?}',
108 ($suffix == 'post') ? $local_part : $local_part . '-' . $suffix,
109 $redirect . $suffix . '@' . $globals->lists->redirect_domain, $domain);
110 }
111 }
112
113 function delete_list($local_part, $domain)
114 {
115 global $globals;
116
117 $redirect = $domain . '_' . $local_part . '+';
118 foreach(array('post', 'owner', 'admin', 'bounces', 'unsubscribe') as $suffix) {
119 XDB::execute('DELETE email_virtual
120 WHERE redirect = {?} AND type = \'list\'',
121 $redirect . $suffix . '@' . $globals->lists->redirect_domain);
122 }
123 }
124
125 function list_exist($local_part, $domain)
126 {
127 return XDB::fetchOneCell('SELECT COUNT(*)
128 FROM email_virtual AS v
129 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
130 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
131 WHERE v.email = {?} AND d.name = {?}',
132 $local_part, $domain);
133 }
134
135 // function mark_broken_email() {{{1
136 function mark_broken_email($email, $admin = false)
137 {
138 $email = valide_email($email);
139 if (empty($email) || $email == '@') {
140 return;
141 }
142
143 $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
144 FROM email_redirect_account AS r1
145 INNER JOIN accounts AS a ON (a.uid = r1.uid)
146 INNER JOIN email_source_account AS s ON (a.uid = s.uid AND s.flags = \'bestalias\')
147 LEFT JOIN email_redirect_account AS r2 ON (a.uid = r2.uid AND r1.redirect != r2.redirect AND
148 r2.broken_level = 0 AND r2.flags = \'active\' AND
149 (r2.type = \'smtp\' OR r2.type = \'googleapps\'))
150 WHERE r1.redirect = {?}
151 GROUP BY r1.uid', $email);
152
153 if ($user) {
154 // Mark address as broken.
155 if (!$user['broken']) {
156 XDB::execute('UPDATE email_redirect_account
157 SET broken_date = NOW(), last = NOW(), broken_level = 1
158 WHERE redirect = {?}', $email);
159 } elseif ($admin) {
160 XDB::execute('UPDATE email_redirect_account
161 SET last = CURDATE(), broken_level = broken_level + 1
162 WHERE redirect = {?} AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
163 $email);
164 } else {
165 XDB::execute('UPDATE email_redirect_account
166 SET broken_level = 1
167 WHERE redirect = {?} AND broken_level = 0', $email);
168 }
169 }
170
171 return $user;
172 }
173
174 // function fix_bestalias() {{{1
175 // Checks for an existing 'bestalias' among the the current user's aliases, and
176 // eventually selects a new bestalias when required.
177 function fix_bestalias(User $user)
178 {
179 // First check if best_domain is properly set.
180 $count = XDB::fetchOneCell('SELECT COUNT(*)
181 FROM accounts AS a
182 INNER JOIN email_virtual_domains AS d ON (d.id = a.best_domain)
183 INNER JOIN email_virtual_domains AS m ON (d.aliasing = m.id)
184 WHERE a.uid = {?} AND m.name = {?}',
185 $user->id(), $user->mainEmailDomain());
186 if ($count == 0) {
187 XDB::execute('UPDATE accounts AS a
188 INNER JOIN email_virtual_domains AS d ON (d.name = {?})
189 SET a.best_domain = d.id
190 WHERE a.uid = {?}',
191 $user->mainEmailDomain(), $user->id());
192 }
193
194 // Then check the alias.
195 $count = XDB::fetchOneCell('SELECT COUNT(*)
196 FROM email_source_account
197 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags) AND expire IS NULL',
198 $user->id());
199
200 if ($count == 1) {
201 return;
202 } elseif ($count > 1) {
203 // If too many bestaliases, delete the bestalias flag from all this
204 // user's emails (this should never happen).
205 XDB::execute("UPDATE email_source_account
206 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
207 WHERE uid = {?}",
208 $user->id());
209 }
210
211 // If no bestalias is selected, we choose the shortest email which is not
212 // related to a usage name and contains a '.'.
213 XDB::execute("UPDATE email_source_account
214 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
215 WHERE uid = {?} AND expire IS NULL
216 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
217 LIMIT 1",
218 $user->id());
219 }
220
221 // function valide_email() {{{1
222 // Returns a cleaned-up version of the @p email string. It removes garbage
223 // characters, and determines the canonical form (without _ and +) for
224 // Polytechnique.org email addresses.
225 function valide_email($str)
226 {
227 global $globals;
228
229 $em = trim(rtrim($str));
230 $em = str_replace('<', '', $em);
231 $em = str_replace('>', '', $em);
232 if (strpos($em, '@') === false) {
233 return;
234 }
235 list($ident, $dom) = explode('@', $em);
236 if (User::isMainMailDomain($dom)) {
237 list($ident1) = explode('_', $ident);
238 list($ident) = explode('+', $ident1);
239 }
240 return $ident . '@' . $dom;
241 }
242
243 // function isvalid_email_redirection() {{{1
244 /** Checks if an email is a suitable redirection.
245 * @param $email the email to check
246 * @return BOOL
247 */
248 function isvalid_email_redirection($email)
249 {
250 return isvalid_email($email) && !preg_match("/@polytechnique\.edu$/", $email) && User::isForeignEmailAddress($email);
251 }
252
253 // function ids_from_mails() {{{1
254 // Converts an array of emails to an array of email => uid, where email is the
255 // given email when we found a matching user.
256 function ids_from_mails(array $emails)
257 {
258 // Removes duplicates, if any.
259 $emails = array_unique($emails);
260
261 // Formats and splits by domain type (locally managed or external) emails.
262 $main_domain_emails = array();
263 $aux_domain_emails = array();
264 $other_emails = array();
265 foreach ($emails as $email) {
266 if (strpos($email, '@') === false) {
267 $main_domain_emails[] = $email;
268 } else {
269 if (User::isForeignEmailAddress($email)) {
270 $other_emails[$email] = strtolower($user . '@' . $domain);
271 } else {
272 list($local_part, $domain) = explode('@', $email);
273 list($local_part) = explode('+', $local_part);
274 list($local_part) = explode('_', $local_part);
275 if (User::isMainMailDomain($domain)) {
276 $main_domain_emails[$email] = strtolower($local_part);
277 } elseif (User::isAliasMailDomain($domain)) {
278 $aux_domain_emails[$email] = strtolower($local_part);
279 }
280 }
281 }
282 }
283
284 // Retrieves emails from our domains.
285 $main_domain_uids = XDB::fetchAllAssoc('email',
286 'SELECT email, uid
287 FROM email_source_account
288 WHERE email IN {?} AND type != \'alias_aux\'',
289 array_unique($main_domain_emails));
290 $aux_domain_uids = XDB::fetchAllAssoc('email',
291 'SELECT email, uid
292 FROM email_source_account
293 WHERE email IN {?} AND type = \'alias_aux\'',
294 array_unique($aux_domain_emails));
295
296 // Retrieves emails from redirections.
297 $other_uids = XDB::fetchAllAssoc('redirect',
298 'SELECT redirect, uid
299 FROM email_redirect_account
300 WHERE redirect IN {?}',
301 array_unique($other_emails));
302
303 // Associates given emails with the corresponding uid.
304 $uids = array();
305 foreach ($main_domain_emails as $email => $key) {
306 $uids[$email] = $main_domain_uids[$key];
307 }
308 foreach ($aux_domain_emails as $email => $key) {
309 $uids[$email] = $aux_domain_uids[$key];
310 }
311 foreach ($other_emails as $email => $key) {
312 $uids[$email] = $other_uids[$key];
313 }
314
315 return array_unique($uids);
316 }
317
318 // class Bogo {{{1
319 // The Bogo class represents a spam filtering level in plat/al architecture.
320 class Bogo
321 {
322 public static $states = array(
323 0 => 'default',
324 1 => 'let_spams',
325 2 => 'tag_spams',
326 3 => 'tag_and_drop_spams',
327 4 => 'drop_spams'
328 );
329
330 private $user;
331 public $state;
332 public $single_state;
333 public $redirections;
334 public $single_redirection;
335
336 public function __construct(User $user)
337 {
338 if (!$user) {
339 return;
340 }
341
342 $this->user = &$user;
343 $res = XDB::fetchOneAssoc('SELECT COUNT(DISTINCT(action)) AS action_count, COUNT(redirect) AS redirect_count, action
344 FROM email_redirect_account
345 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\') AND flags = \'active\'',
346 $user->id());
347 if ($res['redirect_count'] == 0) {
348 return;
349 }
350
351 $this->single_redirection = ($res['redirect_count'] == 1);
352 $this->redirections = XDB::fetchAllAssoc('SELECT IF(type = \'googleapps\', type, redirect) AS redirect, type, action
353 FROM email_redirect_account
354 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')
355 ORDER BY type, redirect',
356 $user->id());
357
358 foreach ($this->redirections AS &$redirection) {
359 $redirection['filter'] = array_search($redirection['action'], self::$states);
360 }
361 if ($res['action_count'] == 1) {
362 $this->state = array_search($res['action'], self::$states);
363 $this->single_state = true;
364 } else {
365 $this->single_state = $this->state = false;
366 }
367 }
368
369 public function changeAll($state)
370 {
371 Platal::assert($state >= 0 && $state < count(self::$states), 'Unknown antispam level.');
372
373 $this->state = $state;
374 XDB::execute('UPDATE email_redirect_account
375 SET action = {?}
376 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
377 self::$states[$this->state], $this->user->id());
378 }
379
380 public function change($redirection, $state)
381 {
382 Platal::assert($state >= 0 && $state < count(self::$states), 'Unknown antispam level.');
383
384 XDB::execute('UPDATE email_redirect_account
385 SET action = {?}
386 WHERE uid = {?} AND (type = {?} OR redirect = {?})',
387 self::$states[$state], $this->user->id(), $redirection, $redirection);
388 }
389 }
390
391 // class Email {{{1
392 // Represents an "email address" used as final recipient for plat/al-managed
393 // addresses.
394 class Email
395 {
396 // Lists fields to load automatically.
397 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
398
399 // Shortname to realname mapping for known mail storage backends.
400 static private $display_names = array(
401 'imap' => 'Accès de secours aux emails (IMAP)',
402 'googleapps' => 'Compte Google Apps',
403 );
404 static private $storage_domains = array(
405 'imap' => 'imap',
406 'googleapps' => 'g'
407 );
408
409 private $user;
410
411 // Basic email properties; $sufficient indicates if the email can be used as
412 // an unique redirection; $redirect contains the delivery email address.
413 public $type;
414 public $sufficient;
415 public $email;
416 public $display_email;
417 public $domain;
418 public $action;
419 public $filter_level;
420
421 // Redirection status properties.
422 public $active;
423 public $inactive;
424 public $broken;
425 public $disabled;
426 public $rewrite;
427 public $allow_rewrite;
428 public $hash;
429
430 // Redirection bounces stats.
431 public $last;
432 public $broken_level;
433 public $broken_date;
434
435 public function __construct(User $user, array $row)
436 {
437 foreach (self::$field_names as $field) {
438 if (array_key_exists($field, $row)) {
439 $this->$field = $row[$field];
440 }
441 }
442 $this->email = $row['redirect'];
443
444 if (array_key_exists($this->type, Email::$display_names)) {
445 $this->display_email = self::$display_names[$this->type];
446 } else {
447 $this->display_email = $this->email;
448 }
449 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
450 $this->$status = ($status == $row['flags']);
451 }
452 $this->sufficient = ($this->type == 'smtp' || $this->type == 'googleapps');
453 $this->filter_level = ($this->type == 'imap') ? null : array_search($this->action, Bogo::$states);
454 $this->user = &$user;
455 }
456
457 // Activates the email address as a redirection.
458 public function activate()
459 {
460 if ($this->inactive) {
461 XDB::execute('UPDATE email_redirect_account
462 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
463 WHERE uid = {?} AND redirect = {?}',
464 $this->user->id(), $this->email);
465 S::logger()->log('email_on', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ''));
466 $this->inactive = false;
467 $this->active = true;
468 }
469 }
470
471 // Deactivates the email address as a redirection.
472 public function deactivate()
473 {
474 if ($this->active) {
475 XDB::execute('UPDATE email_redirect_account
476 SET flags = \'inactive\'
477 WHERE uid = {?} AND redirect = {?}',
478 $this->user->id(), $this->email);
479 S::logger()->log('email_off', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
480 $this->inactive = true;
481 $this->active = false;
482 }
483 }
484
485
486 // Sets the rewrite rule for the given address.
487 public function set_rewrite($rewrite)
488 {
489 if ($this->type != 'smtp' || $this->rewrite == $rewrite) {
490 return;
491 }
492 if (!$rewrite || !isvalid_email($rewrite)) {
493 $rewrite = '';
494 }
495 XDB::execute('UPDATE email_redirect_account
496 SET rewrite = {?}
497 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
498 $rewrite, $this->user->id(), $this->email);
499 $this->rewrite = $rewrite;
500 if (!$this->allow_rewrite) {
501 global $globals;
502 if (empty($this->hash)) {
503 $this->hash = rand_url_id();
504 XDB::execute('UPDATE email_redirect_account
505 SET hash = {?}
506 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
507 $this->hash, $this->user->id(), $this->email);
508 }
509 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
510 $mail->assign('mail', $this);
511 $mail->assign('user', $this->user);
512 $mail->assign('baseurl', $globals->baseurl);
513 $mail->assign('sitename', $globals->core->sitename);
514 $mail->assign('to', $this->email);
515 $mail->send($this->user->isEmailFormatHtml());
516 }
517 }
518
519
520 // Resets the error counts associated with the redirection.
521 public function clean_errors()
522 {
523 if ($this->type != 'smtp') {
524 return;
525 }
526 if (!S::admin()) {
527 return false;
528 }
529 $this->broken = 0;
530 $this->broken_level = 0;
531 $this->last = 0;
532 return XDB::execute('UPDATE email_redirect_account
533 SET broken_level = 0, broken_date = 0, last = 0
534 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
535 $this->user->id(), $this->email);
536 }
537
538
539 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
540 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
541 // can be definitively removed; 'disable' indicates if the email has a third
542 // status 'disabled' in addition to 'active' and 'inactive').
543 public function has_rewrite()
544 {
545 return ($this->type == 'smtp');
546 }
547
548 public function is_removable()
549 {
550 return ($this->type == 'smtp');
551 }
552
553 public function has_disable()
554 {
555 return true;
556 }
557
558 public function is_redirection()
559 {
560 return ($this->type == 'smtp');
561 }
562
563 // Returns the list of allowed storages for the @p user.
564 static private function get_allowed_storages(User $user)
565 {
566 global $globals;
567 $storages = array();
568
569 // Google Apps storage is available for users with valid Google Apps account.
570 require_once 'googleapps.inc.php';
571 if ($globals->mailstorage->googleapps_domain &&
572 GoogleAppsAccount::account_status($user->id()) == 'active') {
573 $storages[] = 'googleapps';
574 }
575
576 // IMAP storage is always visible to administrators, and is allowed for
577 // everyone when the service is marked as 'active'.
578 if ($globals->mailstorage->imap_active || S::admin()) {
579 $storages[] = 'imap';
580 }
581
582 return $storages;
583 }
584
585 static public function activate_storage(User $user, $storage)
586 {
587 Platal::assert(in_array($storage, self::get_allowed_storages($user)));
588
589 if (!self::is_active_storage($user, $storage)) {
590 global $globals;
591
592 XDB::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
593 VALUES ({?}, {?}, {?}, \'active\')',
594 $user->id(), $storage,
595 $user->hruid . '@' . self::$storage_domains[$storage] . '.' . $globals->mail->domain);
596 }
597 }
598
599 static public function deactivate_storage(User $user, $storage)
600 {
601 if (in_array($storage, self::$storage_domains)) {
602 XDB::execute('DELETE FROM email_redirect_account
603 WHERE uid = {?} AND type = {?}',
604 $user->id(), $storage);
605 }
606 }
607
608 static public function is_active_storage(User $user, $storage)
609 {
610 if (!in_array($storage, self::$storage_domains)) {
611 return false;
612 }
613 $res = XDB::fetchOneCell('SELECT COUNT(*)
614 FROM email_redirect_account
615 WHERE uid = {?} AND type = {?} AND flags = \'active\'',
616 $user->id(), $storage);
617 return !is_null($res) && $res > 0;
618 }
619 }
620 // class Redirect {{{1
621 // Redirect is a placeholder class for an user's active redirections (third-party
622 // redirection email, or Polytechnique.org mail storages).
623 class Redirect
624 {
625 private $flags = 'active';
626 private $user;
627
628 public $emails;
629
630 public function __construct(User $user)
631 {
632 $this->user = &$user;
633
634 // Adds third-party email redirections.
635 $res = XDB::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
636 FROM email_redirect_account
637 WHERE uid = {?} AND type != \'homonym\'',
638 $user->id());
639 $this->emails = array();
640 while ($row = $res->next()) {
641 $this->emails[] = new Email($user, $row);
642 }
643 }
644
645 public function other_active($email)
646 {
647 foreach ($this->emails as $mail) {
648 if ($mail->email != $email && $mail->active && $mail->sufficient) {
649 return true;
650 }
651 }
652 return false;
653 }
654
655 public function delete_email($email)
656 {
657 if (!$this->other_active($email)) {
658 return ERROR_INACTIVE_REDIRECTION;
659 }
660 XDB::execute('DELETE FROM email_redirect_account
661 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
662 $this->user->id(), $email);
663 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
664 foreach ($this->emails as $i => $mail) {
665 if ($email == $mail->email) {
666 unset($this->emails[$i]);
667 }
668 }
669 check_redirect($this);
670 $this->update_imap();
671 return SUCCESS;
672 }
673
674 public function add_email($email)
675 {
676 $email_stripped = strtolower(trim($email));
677 if (!isvalid_email($email_stripped)) {
678 return ERROR_INVALID_EMAIL;
679 }
680 if (!isvalid_email_redirection($email_stripped)) {
681 return ERROR_LOOP_EMAIL;
682 }
683 // We first need to retrieve the value for the antispam filter: it is
684 // either the user's redirections common value, or if they differ, our
685 // default value.
686 $bogo = new Bogo($this->user);
687 $filter = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::$states[0]);
688 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
689 XDB::execute('REPLACE INTO email_redirect_account (uid, redirect, flags, action)
690 VALUES ({?}, {?}, \'active\', {?})',
691 $this->user->id(), $email, $filter);
692 if ($logger = S::v('log', null)) { // may be absent --> step4.php
693 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
694 }
695 foreach ($this->emails as $mail) {
696 if ($mail->email == $email_stripped) {
697 return SUCCESS;
698 }
699 }
700 $this->emails[] = new Email($this->user, array(
701 'redirect' => $email,
702 'rewrite' => '',
703 'type' => 'smtp',
704 'action' => $filter,
705 'broken_date' => '0000-00-00',
706 'broken_level' => 0,
707 'last' => '0000-00-00',
708 'flags' => 'active',
709 'hash' => null,
710 'allow_rewrite' => 0
711 ));
712
713 // security stuff
714 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
715 check_redirect($this);
716 $this->update_imap();
717 return SUCCESS;
718 }
719
720 public function modify_email($emails_actifs, $emails_rewrite)
721 {
722 foreach ($this->emails as &$email) {
723 if (in_array($email->email, $emails_actifs)) {
724 $email->activate();
725 } else {
726 $email->deactivate();
727 }
728 $email->set_rewrite($emails_rewrite[$email->email]);
729 }
730 check_redirect($this);
731 $this->update_imap();
732 return SUCCESS;
733 }
734
735 public function modify_one_email($email, $activate)
736 {
737 $allinactive = true;
738 $thisone = false;
739 foreach ($this->emails as $i=>$mail) {
740 if ($mail->email == $email) {
741 $thisone = $i;
742 }
743 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
744 }
745 if ($thisone === false) {
746 return ERROR_INVALID_EMAIL;
747 }
748 if ($allinactive || $activate) {
749 $this->emails[$thisone]->activate();
750 } else {
751 $this->emails[$thisone]->deactivate();
752 }
753 check_redirect($this);
754 $this->update_imap();
755 if ($allinactive && !$activate) {
756 return ERROR_INACTIVE_REDIRECTION;
757 }
758 return SUCCESS;
759 }
760
761 public function modify_one_email_redirect($email, $redirect)
762 {
763 foreach ($this->emails as &$mail) {
764 if ($mail->email == $email) {
765 $mail->set_rewrite($redirect);
766 check_redirect($this);
767 $this->update_imap();
768 return;
769 }
770 }
771 }
772
773 public function clean_errors($email)
774 {
775 foreach ($this->emails as &$mail) {
776 if ($mail->email == $email) {
777 check_redirect($this);
778 $this->update_imap();
779 return $mail->clean_errors();
780 }
781 }
782 return false;
783 }
784
785 public function disable()
786 {
787 XDB::execute("UPDATE email_redirect_account
788 SET flags = 'disable'
789 WHERE flags = 'active' AND uid = {?}", $this->user->id());
790 foreach ($this->emails as &$mail) {
791 if ($mail->active && $mail->has_disable()) {
792 $mail->disabled = true;
793 $mail->active = false;
794 }
795 }
796 check_redirect($this);
797 $this->update_imap();
798 }
799
800 public function enable()
801 {
802 XDB::execute("UPDATE email_redirect_account
803 SET flags = 'active'
804 WHERE flags = 'disable' AND uid = {?}", $this->user->id());
805 foreach ($this->emails as &$mail) {
806 if ($mail->disabled) {
807 $mail->disabled = false;
808 $mail->active = true;
809 }
810 check_redirect($this);
811 }
812 $this->update_imap();
813 }
814
815 public function get_broken_mx()
816 {
817 $res = XDB::query("SELECT host, text
818 FROM mx_watch
819 WHERE state != 'ok'");
820 if (!$res->numRows()) {
821 return array();
822 }
823 $mxs = $res->fetchAllAssoc();
824 $mails = array();
825 foreach ($this->emails as &$mail) {
826 if ($mail->active && strstr($mail->email, '@') !== false) {
827 list(,$domain) = explode('@', $mail->email);
828 getmxrr($domain, $lcl_mxs);
829 if (empty($lcl_mxs)) {
830 $lcl_mxs = array($domain);
831 }
832 $broken = false;
833 foreach ($mxs as &$mx) {
834 foreach ($lcl_mxs as $lcl) {
835 if (fnmatch($mx['host'], $lcl)) {
836 $broken = $mx['text'];
837 break;
838 }
839 }
840 if ($broken) {
841 $mails[] = array('mail' => $mail->email, 'text' => $broken);
842 break;
843 }
844 }
845 }
846 }
847 return $mails;
848 }
849
850 public function active_emails()
851 {
852 $emails = array();
853 foreach ($this->emails as $mail) {
854 if ($mail->active) {
855 $emails[] = $mail;
856 }
857 }
858 return $emails;
859 }
860
861 public function get_uid()
862 {
863 return $this->user->id();
864 }
865
866 private function update_imap()
867 {
868 // Imaps must bounce if and only if the user has no active redirection.
869 if (!$this->other_active('')) {
870 XDB::execute('UPDATE email_redirect_account
871 SET action = \'imap_and_bounce\'
872 WHERE type = \'imap\' AND uid = {?}',
873 $this->user->id());
874 } else {
875 XDB::execute('UPDATE email_redirect_account
876 SET action = \'let_spams\'
877 WHERE type = \'imap\' AND uid = {?}',
878 $this->user->id());
879 }
880 }
881 }
882
883 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
884 ?>