Shows user filter used after a newsletter has been sent (Closes #1526)
[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
ca6980dc
SJ
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.
29function require_email_update(User $user, $new_email)
30{
31 Platal::assert(!is_null($user), 'User cannot be null.');
32
65fae027 33 return !$user->checkPerms(User::PERM_MAIL) && strtolower($new_email) != strtolower($user->forlifeEmail());
ca6980dc
SJ
34}
35
7e82b545 36function format_email_alias($email)
85ddf64f 37{
7e82b545
SJ
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
47function 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 }
85ddf64f
SJ
53
54 XDB::execute('INSERT IGNORE INTO email_virtual (email, domain, redirect, type)
55 SELECT {?}, id, {?}, {?}
56 FROM email_virtual_domains
57 WHERE name = {?}',
7e82b545
SJ
58 $local_part, $email, $type, $domain);
59 return true;
85ddf64f
SJ
60}
61
7e82b545 62function delete_from_list_alias($email, $local_part, $domain, $type = 'alias')
85ddf64f 63{
7e82b545
SJ
64 $email = format_email_alias($email);
65 if (is_null($email)) {
66 return false;
67 }
85ddf64f
SJ
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 = {?}',
7e82b545
SJ
74 $local_part, $domain, $email, $type);
75 return true;
85ddf64f
SJ
76}
77
7e82b545 78function update_list_alias($email, $former_email, $local_part, $domain, $type = 'alias')
7852229b 79{
7e82b545
SJ
80 $email = format_email_alias($email);
81 if (is_null($email)) {
82 return false;
83 }
7852229b
SJ
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 = {?}',
7e82b545
SJ
89 $email, $former_email, $domain, $local_part, $type);
90 return true;
7852229b
SJ
91}
92
ca6980dc
SJ
93// Updates an email in all aliases (groups and events).
94function 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
85ddf64f
SJ
102function 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)
51c2c63a 108 WHERE v.email = {?} AND d.name = {?} AND type = \'alias\'',
85ddf64f
SJ
109 $local_part, $domain);
110
d3a4f32c
SJ
111 $users = array();
112 $nonusers = array();
85ddf64f 113 foreach ($emails as $email) {
d3a4f32c
SJ
114 if ($user = User::getSilent($email)) {
115 $users[] = $user;
116 } else {
117 $nonusers[] = $email;
118 }
85ddf64f
SJ
119 }
120
d3a4f32c
SJ
121 return array(
122 'users' => $users,
123 'nonusers' => $nonusers
124 );
85ddf64f
SJ
125}
126
127function 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)
51c2c63a 133 WHERE v.email = {?} AND d.name = {?} AND type = \'alias\'',
85ddf64f
SJ
134 $local_part, $domain);
135}
136
137function 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)
63112e27 142 WHERE m.name = {?} AND v.type = \'alias\'
85ddf64f
SJ
143 GROUP BY v.email',
144 $domain);
145}
146
147function 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
162function 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) {
30e6bbe3
SJ
168 XDB::execute('DELETE FROM email_virtual
169 WHERE redirect = {?} AND type = \'list\'',
85ddf64f
SJ
170 $redirect . $suffix . '@' . $globals->lists->redirect_domain);
171 }
172}
173
174function 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
a9fd3272
SJ
184// function mark_broken_email() {{{1
185function mark_broken_email($email, $admin = false)
186{
187 $email = valide_email($email);
188 if (empty($email) || $email == '@') {
189 return;
190 }
191
a51d0d30 192 $user = XDB::fetchOneAssoc('SELECT r1.uid, a.hruid, a.full_name, r1.broken_level != 0 AS broken, COUNT(r2.uid) AS nb_mails,
dd092f56 193 s.email AS alias, DATE_ADD(r1.last, INTERVAL 14 DAY) < CURDATE() as notify
a9fd3272
SJ
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
337a6acf 211 SET last = CURDATE(), broken_level = broken_level + 1
a9fd3272
SJ
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
441c2451 224// function fix_bestalias() {{{1
11ed26e5
VZ
225// Checks for an existing 'bestalias' among the the current user's aliases, and
226// eventually selects a new bestalias when required.
26ba053e 227function fix_bestalias(User $user)
0337d704 228{
f067a3d6
SJ
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());
11ed26e5 234
f067a3d6 235 if ($alias_count > 1) {
b4503762
SJ
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 }
f067a3d6
SJ
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
b4503762 273
0337d704 274}
275
441c2451 276// function valide_email() {{{1
11ed26e5
VZ
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.
0337d704 280function valide_email($str)
281{
a3a049fc 282 global $globals;
283
284 $em = trim(rtrim($str));
285 $em = str_replace('<', '', $em);
286 $em = str_replace('>', '', $em);
97664536
SJ
287 if (strpos($em, '@') === false) {
288 return;
289 }
a3a049fc 290 list($ident, $dom) = explode('@', $em);
f036c896 291 if (User::isMainMailDomain($dom)) {
a3a049fc 292 list($ident1) = explode('_', $ident);
293 list($ident) = explode('+', $ident1);
294 }
295 return $ident . '@' . $dom;
0337d704 296}
297
c6310567 298// function isvalid_email_redirection() {{{1
b4503762
SJ
299/** Checks if an email is a suitable redirection.
300 * @param $email the email to check
c6310567
FB
301 * @return BOOL
302 */
303function isvalid_email_redirection($email)
304{
f036c896 305 return isvalid_email($email) && !preg_match("/@polytechnique\.edu$/", $email) && User::isForeignEmailAddress($email);
c6310567
FB
306}
307
180627f3 308// function ids_from_mails() {{{1
b4503762
SJ
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.
180627f3 311function ids_from_mails(array $emails)
1605f171 312{
b4503762
SJ
313 // Removes duplicates, if any.
314 $emails = array_unique($emails);
315
316 // Formats and splits by domain type (locally managed or external) emails.
f036c896
SJ
317 $main_domain_emails = array();
318 $aux_domain_emails = array();
319 $other_emails = array();
1605f171
RB
320 foreach ($emails as $email) {
321 if (strpos($email, '@') === false) {
f036c896 322 $main_domain_emails[] = $email;
1605f171 323 } else {
f036c896
SJ
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 }
1605f171
RB
336 }
337 }
180627f3 338
b4503762 339 // Retrieves emails from our domains.
f036c896
SJ
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));
1605f171 350
b4503762
SJ
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));
1605f171 357
b4503762
SJ
358 // Associates given emails with the corresponding uid.
359 $uids = array();
f036c896
SJ
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];
1605f171
RB
368 }
369
f036c896 370 return array_unique($uids);
1605f171
RB
371}
372
441c2451 373// class Bogo {{{1
11ed26e5 374// The Bogo class represents a spam filtering level in plat/al architecture.
0337d704 375class Bogo
376{
5ad556d3
SJ
377 const MAIN_DEFAULT = 'default';
378 const IMAP_DEFAULT = 'let_spams';
379
1bab8330 380 public static $states = array(
3b346b99
SJ
381 0 => 'default',
382 1 => 'let_spams',
383 2 => 'tag_spams',
384 3 => 'tag_and_drop_spams',
385 4 => 'drop_spams'
386 );
a3a049fc 387
12a587df 388 private $user;
3b346b99
SJ
389 public $state;
390 public $single_state;
391 public $redirections;
392 public $single_redirection;
a3a049fc 393
26ba053e 394 public function __construct(User $user)
0337d704 395 {
12a587df 396 if (!$user) {
3c1e6a1e 397 return;
398 }
11ed26e5 399
12a587df 400 $this->user = &$user;
3b346b99
SJ
401 $res = XDB::fetchOneAssoc('SELECT COUNT(DISTINCT(action)) AS action_count, COUNT(redirect) AS redirect_count, action
402 FROM email_redirect_account
983c2a9a
SJ
403 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\') AND flags = \'active\'
404 GROUP BY uid',
3b346b99
SJ
405 $user->id());
406 if ($res['redirect_count'] == 0) {
b4503762 407 return;
3c1e6a1e 408 }
3b346b99
SJ
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 }
0337d704 426 }
427
3b346b99 428 public function changeAll($state)
0337d704 429 {
3b346b99
SJ
430 Platal::assert($state >= 0 && $state < count(self::$states), 'Unknown antispam level.');
431
432 $this->state = $state;
b4503762
SJ
433 XDB::execute('UPDATE email_redirect_account
434 SET action = {?}
435 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
3b346b99 436 self::$states[$this->state], $this->user->id());
0337d704 437 }
438
3b346b99 439 public function change($redirection, $state)
612a2d8a 440 {
3b346b99
SJ
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);
612a2d8a 447 }
0337d704 448}
449
441c2451 450// class Email {{{1
11ed26e5 451// Represents an "email address" used as final recipient for plat/al-managed
b4503762
SJ
452// addresses.
453class Email
0337d704 454{
b4503762
SJ
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;
612a2d8a 469
11ed26e5 470 // Basic email properties; $sufficient indicates if the email can be used as
b4503762 471 // an unique redirection; $redirect contains the delivery email address.
e4f549fd 472 public $id;
11ed26e5
VZ
473 public $type;
474 public $sufficient;
612a2d8a 475 public $email;
11ed26e5 476 public $display_email;
b4503762
SJ
477 public $domain;
478 public $action;
1bab8330 479 public $filter_level;
11ed26e5
VZ
480
481 // Redirection status properties.
612a2d8a 482 public $active;
b4503762 483 public $inactive;
612a2d8a 484 public $broken;
441c2451 485 public $disabled;
612a2d8a 486 public $rewrite;
3d17e48f
FB
487 public $allow_rewrite;
488 public $hash;
11ed26e5
VZ
489
490 // Redirection bounces stats.
612a2d8a 491 public $last;
b4503762
SJ
492 public $broken_level;
493 public $broken_date;
0337d704 494
b4503762 495 public function __construct(User $user, array $row)
0337d704 496 {
b4503762
SJ
497 foreach (self::$field_names as $field) {
498 if (array_key_exists($field, $row)) {
499 $this->$field = $row[$field];
500 }
501 }
502 $this->email = $row['redirect'];
11ed26e5 503
b4503762
SJ
504 if (array_key_exists($this->type, Email::$display_names)) {
505 $this->display_email = self::$display_names[$this->type];
506 } else {
507 $this->display_email = $this->email;
508 }
509 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
510 $this->$status = ($status == $row['flags']);
511 }
512 $this->sufficient = ($this->type == 'smtp' || $this->type == 'googleapps');
1bab8330 513 $this->filter_level = ($this->type == 'imap') ? null : array_search($this->action, Bogo::$states);
e4f549fd
SJ
514 if (array_key_exists($this->type , self::$storage_domains)) {
515 $this->id = $this->type;
516 } else {
105427e9 517 $this->id = str_replace(array('@', '.'), array('_at_', '_dot_'), $this->email);
e4f549fd 518 }
b4503762 519 $this->user = &$user;
0337d704 520 }
521
b4503762 522 // Activates the email address as a redirection.
11ed26e5 523 public function activate()
0337d704 524 {
b4503762 525 if ($this->inactive) {
35be5845 526 if (in_array($this->type, self::get_allowed_storages($this->user))) {
5ad556d3
SJ
527 self::activate_storage($this->user, $this->type, $this->action);
528 } else {
529 XDB::execute('UPDATE email_redirect_account
530 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
531 WHERE uid = {?} AND redirect = {?}',
532 $this->user->id(), $this->email);
533 }
b4503762
SJ
534 S::logger()->log('email_on', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ''));
535 $this->inactive = false;
536 $this->active = true;
0337d704 537 }
538 }
539
b4503762 540 // Deactivates the email address as a redirection.
11ed26e5 541 public function deactivate()
0337d704 542 {
0337d704 543 if ($this->active) {
35be5845 544 if (in_array($this->type, self::get_allowed_storages($this->user))) {
5ad556d3
SJ
545 self::deactivate_storage($this->user, $this->type);
546 } else {
547 XDB::execute('UPDATE email_redirect_account
548 SET flags = \'inactive\'
549 WHERE uid = {?} AND redirect = {?}',
550 $this->user->id(), $this->email);
551 }
b4503762
SJ
552 S::logger()->log('email_off', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
553 $this->inactive = true;
554 $this->active = false;
0337d704 555 }
556 }
612a2d8a 557
0337d704 558
b4503762 559 // Sets the rewrite rule for the given address.
11ed26e5 560 public function set_rewrite($rewrite)
0337d704 561 {
b4503762 562 if ($this->type != 'smtp' || $this->rewrite == $rewrite) {
0337d704 563 return;
564 }
11ed26e5
VZ
565 if (!$rewrite || !isvalid_email($rewrite)) {
566 $rewrite = '';
12acff5d 567 }
b4503762
SJ
568 XDB::execute('UPDATE email_redirect_account
569 SET rewrite = {?}
570 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
571 $rewrite, $this->user->id(), $this->email);
11ed26e5 572 $this->rewrite = $rewrite;
3d17e48f
FB
573 if (!$this->allow_rewrite) {
574 global $globals;
575 if (empty($this->hash)) {
576 $this->hash = rand_url_id();
b4503762
SJ
577 XDB::execute('UPDATE email_redirect_account
578 SET hash = {?}
579 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
580 $this->hash, $this->user->id(), $this->email);
3d17e48f 581 }
3d17e48f
FB
582 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
583 $mail->assign('mail', $this);
21c7c593 584 $mail->assign('user', $this->user);
3d17e48f 585 $mail->assign('baseurl', $globals->baseurl);
c66de9a0
FB
586 $mail->assign('sitename', $globals->core->sitename);
587 $mail->assign('to', $this->email);
21c7c593 588 $mail->send($this->user->isEmailFormatHtml());
3d17e48f 589 }
0337d704 590 }
591
441c2451 592
b4503762 593 // Resets the error counts associated with the redirection.
11ed26e5 594 public function clean_errors()
441c2451 595 {
b4503762
SJ
596 if ($this->type != 'smtp') {
597 return;
598 }
dd70cd28 599 if (!S::admin()) {
441c2451 600 return false;
601 }
b4503762
SJ
602 $this->broken = 0;
603 $this->broken_level = 0;
604 $this->last = 0;
605 return XDB::execute('UPDATE email_redirect_account
606 SET broken_level = 0, broken_date = 0, last = 0
607 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
12a587df 608 $this->user->id(), $this->email);
11ed26e5
VZ
609 }
610
11ed26e5 611
b4503762
SJ
612 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
613 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
614 // can be definitively removed; 'disable' indicates if the email has a third
615 // status 'disabled' in addition to 'active' and 'inactive').
11ed26e5
VZ
616 public function has_rewrite()
617 {
b4503762 618 return ($this->type == 'smtp');
11ed26e5
VZ
619 }
620
11ed26e5
VZ
621 public function is_removable()
622 {
b4503762 623 return ($this->type == 'smtp');
11ed26e5
VZ
624 }
625
11ed26e5
VZ
626 public function has_disable()
627 {
628 return true;
441c2451 629 }
afde0a3a 630
b4503762 631 public function is_redirection()
afde0a3a 632 {
b4503762 633 return ($this->type == 'smtp');
afde0a3a
VZ
634 }
635
636 // Returns the list of allowed storages for the @p user.
5ad556d3 637 static public function get_allowed_storages(User $user)
afde0a3a
VZ
638 {
639 global $globals;
640 $storages = array();
641
642 // Google Apps storage is available for users with valid Google Apps account.
643 require_once 'googleapps.inc.php';
d058a285
SJ
644 if ($user->checkPerms('gapps') &&
645 $globals->mailstorage->googleapps_domain &&
12a587df 646 GoogleAppsAccount::account_status($user->id()) == 'active') {
afde0a3a
VZ
647 $storages[] = 'googleapps';
648 }
649
650 // IMAP storage is always visible to administrators, and is allowed for
651 // everyone when the service is marked as 'active'.
dd70cd28 652 if ($globals->mailstorage->imap_active || S::admin()) {
afde0a3a
VZ
653 $storages[] = 'imap';
654 }
655
656 return $storages;
657 }
658
5ad556d3
SJ
659 static public function make_storage_redirection(User $user, $storage)
660 {
661 return $user->hruid . '@' . self::$storage_domains[$storage] . '.' . Platal::globals()->mail->domain;
662 }
663
664 static public function activate_storage(User $user, $storage, $action = null)
afde0a3a 665 {
9dd0544e 666 Platal::assert(in_array($storage, self::get_allowed_storages($user)), 'Unknown storage.');
afde0a3a 667
5ad556d3
SJ
668 // We first need to retrieve the value for the antispam filter if not
669 // provided: it is either the user's redirections common value, or if
670 // they differ, our default value.
671 if (is_null($action)) {
672 $bogo = new Bogo($user);
673 $action = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::MAIN_DEFAULT);
674 }
b4503762 675
5ad556d3
SJ
676 if (!self::is_active_storage($user, $storage)) {
677 XDB::execute('INSERT INTO email_redirect_account (uid, type, action, redirect, flags)
678 VALUES ({?}, {?}, {?}, {?}, \'active\')',
679 $user->id(), $storage, $action, self::make_storage_redirection($user, $storage));
b4503762 680 }
afde0a3a
VZ
681 }
682
b4503762 683 static public function deactivate_storage(User $user, $storage)
afde0a3a 684 {
5ad556d3 685 if (in_array($storage, self::get_allowed_storages($user))) {
b4503762
SJ
686 XDB::execute('DELETE FROM email_redirect_account
687 WHERE uid = {?} AND type = {?}',
688 $user->id(), $storage);
689 }
afde0a3a
VZ
690 }
691
b4503762 692 static public function is_active_storage(User $user, $storage)
afde0a3a 693 {
5ad556d3 694 if (!in_array($storage, self::get_allowed_storages($user))) {
b4503762 695 return false;
afde0a3a 696 }
b4503762
SJ
697 $res = XDB::fetchOneCell('SELECT COUNT(*)
698 FROM email_redirect_account
f0a52f1b 699 WHERE uid = {?} AND type = {?} AND flags = \'active\'',
b4503762
SJ
700 $user->id(), $storage);
701 return !is_null($res) && $res > 0;
afde0a3a 702 }
afde0a3a 703}
441c2451 704// class Redirect {{{1
11ed26e5
VZ
705// Redirect is a placeholder class for an user's active redirections (third-party
706// redirection email, or Polytechnique.org mail storages).
0337d704 707class Redirect
708{
b4503762 709 private $flags = 'active';
12a587df 710 private $user;
612a2d8a 711
712 public $emails;
0337d704 713
26ba053e 714 public function __construct(User $user)
0337d704 715 {
12a587df 716 $this->user = &$user;
11ed26e5 717
afde0a3a 718 // Adds third-party email redirections.
b4503762
SJ
719 $res = XDB::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
720 FROM email_redirect_account
721 WHERE uid = {?} AND type != \'homonym\'',
722 $user->id());
723 $this->emails = array();
0337d704 724 while ($row = $res->next()) {
b4503762 725 $this->emails[] = new Email($user, $row);
afde0a3a 726 }
5ad556d3
SJ
727
728 if ($storages = Email::get_allowed_storages($user)) {
729 // We first need to retrieve the value for the antispam filter: it is
730 // either the user's redirections common value, or if they differ, our
731 // default value.
732 $bogo = new Bogo($user);
733 $filter = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::MAIN_DEFAULT);
734
735 foreach ($storages as $storage) {
736 if (!Email::is_active_storage($user, $storage)) {
737 $this->emails[] = new Email($user, array(
738 'redirect' => Email::make_storage_redirection($user, $storage),
739 'rewrite' => '',
740 'type' => $storage,
741 'action' => $filter,
742 'broken_date' => 0,
743 'broken_level' => '0000-00-00',
744 'last' => '0000-00-00',
745 'flags' => 'inactive',
746 'hash' => '',
747 'allow_rewrite' => 0));
748 }
749 }
750 }
0337d704 751 }
752
612a2d8a 753 public function other_active($email)
0337d704 754 {
755 foreach ($this->emails as $mail) {
11ed26e5 756 if ($mail->email != $email && $mail->active && $mail->sufficient) {
0337d704 757 return true;
758 }
759 }
760 return false;
761 }
762
612a2d8a 763 public function delete_email($email)
0337d704 764 {
0337d704 765 if (!$this->other_active($email)) {
766 return ERROR_INACTIVE_REDIRECTION;
767 }
b4503762
SJ
768 XDB::execute('DELETE FROM email_redirect_account
769 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
770 $this->user->id(), $email);
12a587df 771 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
11ed26e5
VZ
772 foreach ($this->emails as $i => $mail) {
773 if ($email == $mail->email) {
0337d704 774 unset($this->emails[$i]);
775 }
3c1e6a1e 776 }
ccdbc270 777 check_redirect($this);
24e8f53b 778 $this->update_imap();
0337d704 779 return SUCCESS;
780 }
781
612a2d8a 782 public function add_email($email)
0337d704 783 {
0337d704 784 $email_stripped = strtolower(trim($email));
785 if (!isvalid_email($email_stripped)) {
786 return ERROR_INVALID_EMAIL;
787 }
788 if (!isvalid_email_redirection($email_stripped)) {
789 return ERROR_LOOP_EMAIL;
790 }
1745c7c8
SJ
791 // We first need to retrieve the value for the antispam filter: it is
792 // either the user's redirections common value, or if they differ, our
793 // default value.
794 $bogo = new Bogo($this->user);
5ad556d3 795 $filter = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::MAIN_DEFAULT);
00ba8a74 796 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
1745c7c8
SJ
797 XDB::execute('REPLACE INTO email_redirect_account (uid, redirect, flags, action)
798 VALUES ({?}, {?}, \'active\', {?})',
799 $this->user->id(), $email, $filter);
3c1e6a1e 800 if ($logger = S::v('log', null)) { // may be absent --> step4.php
12a587df 801 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
0337d704 802 }
3c1e6a1e 803 foreach ($this->emails as $mail) {
804 if ($mail->email == $email_stripped) {
0337d704 805 return SUCCESS;
806 }
3c1e6a1e 807 }
b4503762
SJ
808 $this->emails[] = new Email($this->user, array(
809 'redirect' => $email,
810 'rewrite' => '',
811 'type' => 'smtp',
1745c7c8 812 'action' => $filter,
b4503762
SJ
813 'broken_date' => '0000-00-00',
814 'broken_level' => 0,
815 'last' => '0000-00-00',
816 'flags' => 'active',
817 'hash' => null,
818 'allow_rewrite' => 0
819 ));
ca6d07f4 820
821 // security stuff
12a587df 822 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
ccdbc270 823 check_redirect($this);
24e8f53b 824 $this->update_imap();
0337d704 825 return SUCCESS;
826 }
827
612a2d8a 828 public function modify_email($emails_actifs, $emails_rewrite)
0337d704 829 {
b4503762
SJ
830 foreach ($this->emails as &$email) {
831 if (in_array($email->email, $emails_actifs)) {
832 $email->activate();
3c1e6a1e 833 } else {
b4503762 834 $email->deactivate();
3c1e6a1e 835 }
b4503762 836 $email->set_rewrite($emails_rewrite[$email->email]);
0337d704 837 }
ccdbc270 838 check_redirect($this);
24e8f53b 839 $this->update_imap();
b4503762 840 return SUCCESS;
0337d704 841 }
842
eaf30d86 843 public function modify_one_email($email, $activate)
ccdbc270 844 {
b7582015 845 $allinactive = true;
846 $thisone = false;
8ffa657a 847 foreach ($this->emails as $i=>$mail) {
848 if ($mail->email == $email) {
b7582015 849 $thisone = $i;
8ffa657a 850 }
11ed26e5 851 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
8ffa657a 852 }
b7582015 853 if ($thisone === false) {
854 return ERROR_INVALID_EMAIL;
855 }
ccdbc270 856 if ($allinactive || $activate) {
11ed26e5 857 $this->emails[$thisone]->activate();
ccdbc270 858 } else {
11ed26e5 859 $this->emails[$thisone]->deactivate();
ccdbc270 860 }
861 check_redirect($this);
24e8f53b 862 $this->update_imap();
b7582015 863 if ($allinactive && !$activate) {
864 return ERROR_INACTIVE_REDIRECTION;
eaf30d86 865 }
b4503762 866 return SUCCESS;
8ffa657a 867 }
868
612a2d8a 869 public function modify_one_email_redirect($email, $redirect)
870 {
441c2451 871 foreach ($this->emails as &$mail) {
612a2d8a 872 if ($mail->email == $email) {
11ed26e5 873 $mail->set_rewrite($redirect);
ccdbc270 874 check_redirect($this);
24e8f53b 875 $this->update_imap();
ccdbc270 876 return;
612a2d8a 877 }
878 }
879 }
441c2451 880
11ed26e5 881 public function clean_errors($email)
441c2451 882 {
883 foreach ($this->emails as &$mail) {
884 if ($mail->email == $email) {
e1547442 885 check_redirect($this);
24e8f53b 886 $this->update_imap();
11ed26e5 887 return $mail->clean_errors();
441c2451 888 }
889 }
890 return false;
891 }
892
441c2451 893 public function disable()
894 {
b4503762 895 XDB::execute("UPDATE email_redirect_account
441c2451 896 SET flags = 'disable'
20398e42 897 WHERE flags = 'active' AND uid = {?}", $this->user->id());
441c2451 898 foreach ($this->emails as &$mail) {
11ed26e5 899 if ($mail->active && $mail->has_disable()) {
441c2451 900 $mail->disabled = true;
901 $mail->active = false;
902 }
903 }
e1547442 904 check_redirect($this);
24e8f53b 905 $this->update_imap();
441c2451 906 }
907
441c2451 908 public function enable()
909 {
b4503762 910 XDB::execute("UPDATE email_redirect_account
441c2451 911 SET flags = 'active'
20398e42 912 WHERE flags = 'disable' AND uid = {?}", $this->user->id());
441c2451 913 foreach ($this->emails as &$mail) {
914 if ($mail->disabled) {
441c2451 915 $mail->disabled = false;
b4503762 916 $mail->active = true;
441c2451 917 }
e1547442 918 check_redirect($this);
441c2451 919 }
24e8f53b 920 $this->update_imap();
441c2451 921 }
922
612a2d8a 923 public function get_broken_mx()
ccdbc270 924 {
3083bd93 925 $res = XDB::query("SELECT host, text
8af1d78f
FB
926 FROM mx_watch
927 WHERE state != 'ok'");
120bd636 928 if (!$res->numRows()) {
ccdbc270 929 return array();
930 }
c754cf5b 931 $mxs = $res->fetchAllAssoc();
ccdbc270 932 $mails = array();
933 foreach ($this->emails as &$mail) {
11ed26e5 934 if ($mail->active && strstr($mail->email, '@') !== false) {
ccdbc270 935 list(,$domain) = explode('@', $mail->email);
936 getmxrr($domain, $lcl_mxs);
937 if (empty($lcl_mxs)) {
938 $lcl_mxs = array($domain);
939 }
940 $broken = false;
941 foreach ($mxs as &$mx) {
942 foreach ($lcl_mxs as $lcl) {
c754cf5b 943 if (fnmatch($mx['host'], $lcl)) {
ccdbc270 944 $broken = $mx['text'];
945 break;
946 }
947 }
948 if ($broken) {
3083bd93 949 $mails[] = array('mail' => $mail->email, 'text' => $broken);
f653ff3d 950 break;
ccdbc270 951 }
952 }
953 }
954 }
955 return $mails;
956 }
e97e9b8f 957
e97e9b8f
VZ
958 public function active_emails()
959 {
960 $emails = array();
961 foreach ($this->emails as $mail) {
962 if ($mail->active) {
963 $emails[] = $mail;
964 }
965 }
966 return $emails;
967 }
45282934 968
45282934
VZ
969 public function get_uid()
970 {
12a587df 971 return $this->user->id();
45282934 972 }
24e8f53b
SJ
973
974 private function update_imap()
975 {
976 // Imaps must bounce if and only if the user has no active redirection.
977 if (!$this->other_active('')) {
978 XDB::execute('UPDATE email_redirect_account
979 SET action = \'imap_and_bounce\'
980 WHERE type = \'imap\' AND uid = {?}',
981 $this->user->id());
982 } else {
983 XDB::execute('UPDATE email_redirect_account
984 SET action = \'let_spams\'
985 WHERE type = \'imap\' AND uid = {?}',
986 $this->user->id());
987 }
988 }
0337d704 989}
990
a7de4ef7 991// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 992?>