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