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