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