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