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