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