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