Enables @polytechnique.edu adresses for old promotions (Closes #1516)
[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
f4dda5fb 301 * @param $user the user asking for the redirection
c6310567
FB
302 * @return BOOL
303 */
f4dda5fb 304function isvalid_email_redirection($email, User $user)
c6310567 305{
f4dda5fb
BG
306 $valid = isvalid_email($email) && User::isForeignEmailAddress($email);
307 if (!$user->hasProfile() || ($user->profile()->grad_year > date('Y') - 3)) {
308 return $valid && !preg_match("/@polytechnique\.edu$/", $email);
309 } else {
310 return $valid;
311 }
c6310567
FB
312}
313
180627f3 314// function ids_from_mails() {{{1
b4503762
SJ
315// Converts an array of emails to an array of email => uid, where email is the
316// given email when we found a matching user.
180627f3 317function ids_from_mails(array $emails)
1605f171 318{
b4503762
SJ
319 // Removes duplicates, if any.
320 $emails = array_unique($emails);
321
322 // Formats and splits by domain type (locally managed or external) emails.
f036c896
SJ
323 $main_domain_emails = array();
324 $aux_domain_emails = array();
325 $other_emails = array();
1605f171
RB
326 foreach ($emails as $email) {
327 if (strpos($email, '@') === false) {
f036c896 328 $main_domain_emails[] = $email;
1605f171 329 } else {
f036c896
SJ
330 if (User::isForeignEmailAddress($email)) {
331 $other_emails[$email] = strtolower($user . '@' . $domain);
332 } else {
333 list($local_part, $domain) = explode('@', $email);
334 list($local_part) = explode('+', $local_part);
335 list($local_part) = explode('_', $local_part);
336 if (User::isMainMailDomain($domain)) {
337 $main_domain_emails[$email] = strtolower($local_part);
338 } elseif (User::isAliasMailDomain($domain)) {
339 $aux_domain_emails[$email] = strtolower($local_part);
340 }
341 }
1605f171
RB
342 }
343 }
180627f3 344
b4503762 345 // Retrieves emails from our domains.
f036c896
SJ
346 $main_domain_uids = XDB::fetchAllAssoc('email',
347 'SELECT email, uid
348 FROM email_source_account
349 WHERE email IN {?} AND type != \'alias_aux\'',
350 array_unique($main_domain_emails));
351 $aux_domain_uids = XDB::fetchAllAssoc('email',
352 'SELECT email, uid
353 FROM email_source_account
354 WHERE email IN {?} AND type = \'alias_aux\'',
355 array_unique($aux_domain_emails));
1605f171 356
b4503762
SJ
357 // Retrieves emails from redirections.
358 $other_uids = XDB::fetchAllAssoc('redirect',
359 'SELECT redirect, uid
360 FROM email_redirect_account
361 WHERE redirect IN {?}',
362 array_unique($other_emails));
1605f171 363
b4503762
SJ
364 // Associates given emails with the corresponding uid.
365 $uids = array();
f036c896
SJ
366 foreach ($main_domain_emails as $email => $key) {
367 $uids[$email] = $main_domain_uids[$key];
368 }
369 foreach ($aux_domain_emails as $email => $key) {
370 $uids[$email] = $aux_domain_uids[$key];
371 }
372 foreach ($other_emails as $email => $key) {
373 $uids[$email] = $other_uids[$key];
1605f171
RB
374 }
375
f036c896 376 return array_unique($uids);
1605f171
RB
377}
378
441c2451 379// class Bogo {{{1
11ed26e5 380// The Bogo class represents a spam filtering level in plat/al architecture.
0337d704 381class Bogo
382{
5ad556d3
SJ
383 const MAIN_DEFAULT = 'default';
384 const IMAP_DEFAULT = 'let_spams';
385
1bab8330 386 public static $states = array(
3b346b99
SJ
387 0 => 'default',
388 1 => 'let_spams',
389 2 => 'tag_spams',
390 3 => 'tag_and_drop_spams',
391 4 => 'drop_spams'
392 );
a3a049fc 393
12a587df 394 private $user;
3b346b99
SJ
395 public $state;
396 public $single_state;
397 public $redirections;
398 public $single_redirection;
a3a049fc 399
26ba053e 400 public function __construct(User $user)
0337d704 401 {
12a587df 402 if (!$user) {
3c1e6a1e 403 return;
404 }
11ed26e5 405
12a587df 406 $this->user = &$user;
3b346b99
SJ
407 $res = XDB::fetchOneAssoc('SELECT COUNT(DISTINCT(action)) AS action_count, COUNT(redirect) AS redirect_count, action
408 FROM email_redirect_account
983c2a9a
SJ
409 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\') AND flags = \'active\'
410 GROUP BY uid',
3b346b99
SJ
411 $user->id());
412 if ($res['redirect_count'] == 0) {
b4503762 413 return;
3c1e6a1e 414 }
3b346b99
SJ
415
416 $this->single_redirection = ($res['redirect_count'] == 1);
417 $this->redirections = XDB::fetchAllAssoc('SELECT IF(type = \'googleapps\', type, redirect) AS redirect, type, action
418 FROM email_redirect_account
419 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')
420 ORDER BY type, redirect',
421 $user->id());
422
423 foreach ($this->redirections AS &$redirection) {
424 $redirection['filter'] = array_search($redirection['action'], self::$states);
425 }
426 if ($res['action_count'] == 1) {
427 $this->state = array_search($res['action'], self::$states);
428 $this->single_state = true;
429 } else {
430 $this->single_state = $this->state = false;
431 }
0337d704 432 }
433
3b346b99 434 public function changeAll($state)
0337d704 435 {
3b346b99
SJ
436 Platal::assert($state >= 0 && $state < count(self::$states), 'Unknown antispam level.');
437
438 $this->state = $state;
b4503762
SJ
439 XDB::execute('UPDATE email_redirect_account
440 SET action = {?}
441 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
3b346b99 442 self::$states[$this->state], $this->user->id());
0337d704 443 }
444
3b346b99 445 public function change($redirection, $state)
612a2d8a 446 {
3b346b99
SJ
447 Platal::assert($state >= 0 && $state < count(self::$states), 'Unknown antispam level.');
448
449 XDB::execute('UPDATE email_redirect_account
450 SET action = {?}
451 WHERE uid = {?} AND (type = {?} OR redirect = {?})',
452 self::$states[$state], $this->user->id(), $redirection, $redirection);
612a2d8a 453 }
0337d704 454}
455
441c2451 456// class Email {{{1
11ed26e5 457// Represents an "email address" used as final recipient for plat/al-managed
b4503762
SJ
458// addresses.
459class Email
0337d704 460{
b4503762
SJ
461 // Lists fields to load automatically.
462 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
463
464 // Shortname to realname mapping for known mail storage backends.
465 static private $display_names = array(
466 'imap' => 'Accès de secours aux emails (IMAP)',
467 'googleapps' => 'Compte Google Apps',
468 );
469 static private $storage_domains = array(
470 'imap' => 'imap',
471 'googleapps' => 'g'
472 );
473
474 private $user;
612a2d8a 475
11ed26e5 476 // Basic email properties; $sufficient indicates if the email can be used as
b4503762 477 // an unique redirection; $redirect contains the delivery email address.
e4f549fd 478 public $id;
11ed26e5
VZ
479 public $type;
480 public $sufficient;
612a2d8a 481 public $email;
11ed26e5 482 public $display_email;
b4503762
SJ
483 public $domain;
484 public $action;
1bab8330 485 public $filter_level;
11ed26e5
VZ
486
487 // Redirection status properties.
612a2d8a 488 public $active;
b4503762 489 public $inactive;
612a2d8a 490 public $broken;
441c2451 491 public $disabled;
612a2d8a 492 public $rewrite;
3d17e48f
FB
493 public $allow_rewrite;
494 public $hash;
11ed26e5
VZ
495
496 // Redirection bounces stats.
612a2d8a 497 public $last;
b4503762
SJ
498 public $broken_level;
499 public $broken_date;
0337d704 500
b4503762 501 public function __construct(User $user, array $row)
0337d704 502 {
b4503762
SJ
503 foreach (self::$field_names as $field) {
504 if (array_key_exists($field, $row)) {
505 $this->$field = $row[$field];
506 }
507 }
508 $this->email = $row['redirect'];
11ed26e5 509
b4503762
SJ
510 if (array_key_exists($this->type, Email::$display_names)) {
511 $this->display_email = self::$display_names[$this->type];
512 } else {
513 $this->display_email = $this->email;
514 }
515 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
516 $this->$status = ($status == $row['flags']);
517 }
518 $this->sufficient = ($this->type == 'smtp' || $this->type == 'googleapps');
1bab8330 519 $this->filter_level = ($this->type == 'imap') ? null : array_search($this->action, Bogo::$states);
e4f549fd
SJ
520 if (array_key_exists($this->type , self::$storage_domains)) {
521 $this->id = $this->type;
522 } else {
105427e9 523 $this->id = str_replace(array('@', '.'), array('_at_', '_dot_'), $this->email);
e4f549fd 524 }
b4503762 525 $this->user = &$user;
0337d704 526 }
527
b4503762 528 // Activates the email address as a redirection.
11ed26e5 529 public function activate()
0337d704 530 {
b4503762 531 if ($this->inactive) {
35be5845 532 if (in_array($this->type, self::get_allowed_storages($this->user))) {
5ad556d3
SJ
533 self::activate_storage($this->user, $this->type, $this->action);
534 } else {
535 XDB::execute('UPDATE email_redirect_account
536 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
537 WHERE uid = {?} AND redirect = {?}',
538 $this->user->id(), $this->email);
539 }
b4503762
SJ
540 S::logger()->log('email_on', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ''));
541 $this->inactive = false;
542 $this->active = true;
0337d704 543 }
544 }
545
b4503762 546 // Deactivates the email address as a redirection.
11ed26e5 547 public function deactivate()
0337d704 548 {
0337d704 549 if ($this->active) {
35be5845 550 if (in_array($this->type, self::get_allowed_storages($this->user))) {
5ad556d3
SJ
551 self::deactivate_storage($this->user, $this->type);
552 } else {
553 XDB::execute('UPDATE email_redirect_account
554 SET flags = \'inactive\'
555 WHERE uid = {?} AND redirect = {?}',
556 $this->user->id(), $this->email);
557 }
b4503762
SJ
558 S::logger()->log('email_off', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
559 $this->inactive = true;
560 $this->active = false;
0337d704 561 }
562 }
612a2d8a 563
0337d704 564
b4503762 565 // Sets the rewrite rule for the given address.
11ed26e5 566 public function set_rewrite($rewrite)
0337d704 567 {
b4503762 568 if ($this->type != 'smtp' || $this->rewrite == $rewrite) {
0337d704 569 return;
570 }
11ed26e5
VZ
571 if (!$rewrite || !isvalid_email($rewrite)) {
572 $rewrite = '';
12acff5d 573 }
b4503762
SJ
574 XDB::execute('UPDATE email_redirect_account
575 SET rewrite = {?}
576 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
577 $rewrite, $this->user->id(), $this->email);
11ed26e5 578 $this->rewrite = $rewrite;
3d17e48f
FB
579 if (!$this->allow_rewrite) {
580 global $globals;
581 if (empty($this->hash)) {
582 $this->hash = rand_url_id();
b4503762
SJ
583 XDB::execute('UPDATE email_redirect_account
584 SET hash = {?}
585 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
586 $this->hash, $this->user->id(), $this->email);
3d17e48f 587 }
3d17e48f
FB
588 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
589 $mail->assign('mail', $this);
21c7c593 590 $mail->assign('user', $this->user);
3d17e48f 591 $mail->assign('baseurl', $globals->baseurl);
c66de9a0
FB
592 $mail->assign('sitename', $globals->core->sitename);
593 $mail->assign('to', $this->email);
21c7c593 594 $mail->send($this->user->isEmailFormatHtml());
3d17e48f 595 }
0337d704 596 }
597
441c2451 598
b4503762 599 // Resets the error counts associated with the redirection.
11ed26e5 600 public function clean_errors()
441c2451 601 {
b4503762
SJ
602 if ($this->type != 'smtp') {
603 return;
604 }
dd70cd28 605 if (!S::admin()) {
441c2451 606 return false;
607 }
b4503762
SJ
608 $this->broken = 0;
609 $this->broken_level = 0;
610 $this->last = 0;
611 return XDB::execute('UPDATE email_redirect_account
612 SET broken_level = 0, broken_date = 0, last = 0
613 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
12a587df 614 $this->user->id(), $this->email);
11ed26e5
VZ
615 }
616
11ed26e5 617
b4503762
SJ
618 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
619 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
620 // can be definitively removed; 'disable' indicates if the email has a third
621 // status 'disabled' in addition to 'active' and 'inactive').
11ed26e5
VZ
622 public function has_rewrite()
623 {
b4503762 624 return ($this->type == 'smtp');
11ed26e5
VZ
625 }
626
11ed26e5
VZ
627 public function is_removable()
628 {
b4503762 629 return ($this->type == 'smtp');
11ed26e5
VZ
630 }
631
11ed26e5
VZ
632 public function has_disable()
633 {
634 return true;
441c2451 635 }
afde0a3a 636
b4503762 637 public function is_redirection()
afde0a3a 638 {
b4503762 639 return ($this->type == 'smtp');
afde0a3a
VZ
640 }
641
642 // Returns the list of allowed storages for the @p user.
5ad556d3 643 static public function get_allowed_storages(User $user)
afde0a3a
VZ
644 {
645 global $globals;
646 $storages = array();
647
648 // Google Apps storage is available for users with valid Google Apps account.
649 require_once 'googleapps.inc.php';
d058a285
SJ
650 if ($user->checkPerms('gapps') &&
651 $globals->mailstorage->googleapps_domain &&
12a587df 652 GoogleAppsAccount::account_status($user->id()) == 'active') {
afde0a3a
VZ
653 $storages[] = 'googleapps';
654 }
655
656 // IMAP storage is always visible to administrators, and is allowed for
657 // everyone when the service is marked as 'active'.
dd70cd28 658 if ($globals->mailstorage->imap_active || S::admin()) {
afde0a3a
VZ
659 $storages[] = 'imap';
660 }
661
662 return $storages;
663 }
664
5ad556d3
SJ
665 static public function make_storage_redirection(User $user, $storage)
666 {
667 return $user->hruid . '@' . self::$storage_domains[$storage] . '.' . Platal::globals()->mail->domain;
668 }
669
670 static public function activate_storage(User $user, $storage, $action = null)
afde0a3a 671 {
9dd0544e 672 Platal::assert(in_array($storage, self::get_allowed_storages($user)), 'Unknown storage.');
afde0a3a 673
5ad556d3
SJ
674 // We first need to retrieve the value for the antispam filter if not
675 // provided: it is either the user's redirections common value, or if
676 // they differ, our default value.
677 if (is_null($action)) {
678 $bogo = new Bogo($user);
679 $action = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::MAIN_DEFAULT);
680 }
b4503762 681
5ad556d3
SJ
682 if (!self::is_active_storage($user, $storage)) {
683 XDB::execute('INSERT INTO email_redirect_account (uid, type, action, redirect, flags)
684 VALUES ({?}, {?}, {?}, {?}, \'active\')',
685 $user->id(), $storage, $action, self::make_storage_redirection($user, $storage));
b4503762 686 }
afde0a3a
VZ
687 }
688
b4503762 689 static public function deactivate_storage(User $user, $storage)
afde0a3a 690 {
5ad556d3 691 if (in_array($storage, self::get_allowed_storages($user))) {
b4503762
SJ
692 XDB::execute('DELETE FROM email_redirect_account
693 WHERE uid = {?} AND type = {?}',
694 $user->id(), $storage);
695 }
afde0a3a
VZ
696 }
697
b4503762 698 static public function is_active_storage(User $user, $storage)
afde0a3a 699 {
5ad556d3 700 if (!in_array($storage, self::get_allowed_storages($user))) {
b4503762 701 return false;
afde0a3a 702 }
b4503762
SJ
703 $res = XDB::fetchOneCell('SELECT COUNT(*)
704 FROM email_redirect_account
f0a52f1b 705 WHERE uid = {?} AND type = {?} AND flags = \'active\'',
b4503762
SJ
706 $user->id(), $storage);
707 return !is_null($res) && $res > 0;
afde0a3a 708 }
afde0a3a 709}
441c2451 710// class Redirect {{{1
11ed26e5
VZ
711// Redirect is a placeholder class for an user's active redirections (third-party
712// redirection email, or Polytechnique.org mail storages).
0337d704 713class Redirect
714{
b4503762 715 private $flags = 'active';
12a587df 716 private $user;
612a2d8a 717
718 public $emails;
0337d704 719
26ba053e 720 public function __construct(User $user)
0337d704 721 {
12a587df 722 $this->user = &$user;
11ed26e5 723
afde0a3a 724 // Adds third-party email redirections.
b4503762
SJ
725 $res = XDB::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
726 FROM email_redirect_account
727 WHERE uid = {?} AND type != \'homonym\'',
728 $user->id());
729 $this->emails = array();
0337d704 730 while ($row = $res->next()) {
b4503762 731 $this->emails[] = new Email($user, $row);
afde0a3a 732 }
5ad556d3
SJ
733
734 if ($storages = Email::get_allowed_storages($user)) {
735 // We first need to retrieve the value for the antispam filter: it is
736 // either the user's redirections common value, or if they differ, our
737 // default value.
738 $bogo = new Bogo($user);
739 $filter = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::MAIN_DEFAULT);
740
741 foreach ($storages as $storage) {
742 if (!Email::is_active_storage($user, $storage)) {
743 $this->emails[] = new Email($user, array(
744 'redirect' => Email::make_storage_redirection($user, $storage),
745 'rewrite' => '',
746 'type' => $storage,
747 'action' => $filter,
748 'broken_date' => 0,
749 'broken_level' => '0000-00-00',
750 'last' => '0000-00-00',
751 'flags' => 'inactive',
752 'hash' => '',
753 'allow_rewrite' => 0));
754 }
755 }
756 }
0337d704 757 }
758
612a2d8a 759 public function other_active($email)
0337d704 760 {
761 foreach ($this->emails as $mail) {
11ed26e5 762 if ($mail->email != $email && $mail->active && $mail->sufficient) {
0337d704 763 return true;
764 }
765 }
766 return false;
767 }
768
612a2d8a 769 public function delete_email($email)
0337d704 770 {
0337d704 771 if (!$this->other_active($email)) {
772 return ERROR_INACTIVE_REDIRECTION;
773 }
b4503762
SJ
774 XDB::execute('DELETE FROM email_redirect_account
775 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
776 $this->user->id(), $email);
12a587df 777 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
11ed26e5
VZ
778 foreach ($this->emails as $i => $mail) {
779 if ($email == $mail->email) {
0337d704 780 unset($this->emails[$i]);
781 }
3c1e6a1e 782 }
ccdbc270 783 check_redirect($this);
24e8f53b 784 $this->update_imap();
0337d704 785 return SUCCESS;
786 }
787
612a2d8a 788 public function add_email($email)
0337d704 789 {
0337d704 790 $email_stripped = strtolower(trim($email));
791 if (!isvalid_email($email_stripped)) {
792 return ERROR_INVALID_EMAIL;
793 }
f4dda5fb 794 if (!isvalid_email_redirection($email_stripped, $this->user)) {
0337d704 795 return ERROR_LOOP_EMAIL;
796 }
1745c7c8
SJ
797 // We first need to retrieve the value for the antispam filter: it is
798 // either the user's redirections common value, or if they differ, our
799 // default value.
800 $bogo = new Bogo($this->user);
5ad556d3 801 $filter = ($bogo->single_state ? Bogo::$states[$bogo->state] : Bogo::MAIN_DEFAULT);
00ba8a74 802 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
1745c7c8
SJ
803 XDB::execute('REPLACE INTO email_redirect_account (uid, redirect, flags, action)
804 VALUES ({?}, {?}, \'active\', {?})',
805 $this->user->id(), $email, $filter);
3c1e6a1e 806 if ($logger = S::v('log', null)) { // may be absent --> step4.php
12a587df 807 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
0337d704 808 }
3c1e6a1e 809 foreach ($this->emails as $mail) {
810 if ($mail->email == $email_stripped) {
0337d704 811 return SUCCESS;
812 }
3c1e6a1e 813 }
b4503762
SJ
814 $this->emails[] = new Email($this->user, array(
815 'redirect' => $email,
816 'rewrite' => '',
817 'type' => 'smtp',
1745c7c8 818 'action' => $filter,
b4503762
SJ
819 'broken_date' => '0000-00-00',
820 'broken_level' => 0,
821 'last' => '0000-00-00',
822 'flags' => 'active',
823 'hash' => null,
824 'allow_rewrite' => 0
825 ));
ca6d07f4 826
827 // security stuff
12a587df 828 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
ccdbc270 829 check_redirect($this);
24e8f53b 830 $this->update_imap();
0337d704 831 return SUCCESS;
832 }
833
612a2d8a 834 public function modify_email($emails_actifs, $emails_rewrite)
0337d704 835 {
b4503762
SJ
836 foreach ($this->emails as &$email) {
837 if (in_array($email->email, $emails_actifs)) {
838 $email->activate();
3c1e6a1e 839 } else {
b4503762 840 $email->deactivate();
3c1e6a1e 841 }
b4503762 842 $email->set_rewrite($emails_rewrite[$email->email]);
0337d704 843 }
ccdbc270 844 check_redirect($this);
24e8f53b 845 $this->update_imap();
b4503762 846 return SUCCESS;
0337d704 847 }
848
eaf30d86 849 public function modify_one_email($email, $activate)
ccdbc270 850 {
b7582015 851 $allinactive = true;
852 $thisone = false;
8ffa657a 853 foreach ($this->emails as $i=>$mail) {
854 if ($mail->email == $email) {
b7582015 855 $thisone = $i;
8ffa657a 856 }
11ed26e5 857 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
8ffa657a 858 }
b7582015 859 if ($thisone === false) {
860 return ERROR_INVALID_EMAIL;
861 }
ccdbc270 862 if ($allinactive || $activate) {
11ed26e5 863 $this->emails[$thisone]->activate();
ccdbc270 864 } else {
11ed26e5 865 $this->emails[$thisone]->deactivate();
ccdbc270 866 }
867 check_redirect($this);
24e8f53b 868 $this->update_imap();
b7582015 869 if ($allinactive && !$activate) {
870 return ERROR_INACTIVE_REDIRECTION;
eaf30d86 871 }
b4503762 872 return SUCCESS;
8ffa657a 873 }
874
612a2d8a 875 public function modify_one_email_redirect($email, $redirect)
876 {
441c2451 877 foreach ($this->emails as &$mail) {
612a2d8a 878 if ($mail->email == $email) {
11ed26e5 879 $mail->set_rewrite($redirect);
ccdbc270 880 check_redirect($this);
24e8f53b 881 $this->update_imap();
ccdbc270 882 return;
612a2d8a 883 }
884 }
885 }
441c2451 886
11ed26e5 887 public function clean_errors($email)
441c2451 888 {
889 foreach ($this->emails as &$mail) {
890 if ($mail->email == $email) {
e1547442 891 check_redirect($this);
24e8f53b 892 $this->update_imap();
11ed26e5 893 return $mail->clean_errors();
441c2451 894 }
895 }
896 return false;
897 }
898
441c2451 899 public function disable()
900 {
b4503762 901 XDB::execute("UPDATE email_redirect_account
441c2451 902 SET flags = 'disable'
20398e42 903 WHERE flags = 'active' AND uid = {?}", $this->user->id());
441c2451 904 foreach ($this->emails as &$mail) {
11ed26e5 905 if ($mail->active && $mail->has_disable()) {
441c2451 906 $mail->disabled = true;
907 $mail->active = false;
908 }
909 }
e1547442 910 check_redirect($this);
24e8f53b 911 $this->update_imap();
441c2451 912 }
913
441c2451 914 public function enable()
915 {
b4503762 916 XDB::execute("UPDATE email_redirect_account
441c2451 917 SET flags = 'active'
20398e42 918 WHERE flags = 'disable' AND uid = {?}", $this->user->id());
441c2451 919 foreach ($this->emails as &$mail) {
920 if ($mail->disabled) {
441c2451 921 $mail->disabled = false;
b4503762 922 $mail->active = true;
441c2451 923 }
e1547442 924 check_redirect($this);
441c2451 925 }
24e8f53b 926 $this->update_imap();
441c2451 927 }
928
612a2d8a 929 public function get_broken_mx()
ccdbc270 930 {
3083bd93 931 $res = XDB::query("SELECT host, text
8af1d78f
FB
932 FROM mx_watch
933 WHERE state != 'ok'");
120bd636 934 if (!$res->numRows()) {
ccdbc270 935 return array();
936 }
c754cf5b 937 $mxs = $res->fetchAllAssoc();
ccdbc270 938 $mails = array();
939 foreach ($this->emails as &$mail) {
11ed26e5 940 if ($mail->active && strstr($mail->email, '@') !== false) {
ccdbc270 941 list(,$domain) = explode('@', $mail->email);
942 getmxrr($domain, $lcl_mxs);
943 if (empty($lcl_mxs)) {
944 $lcl_mxs = array($domain);
945 }
946 $broken = false;
947 foreach ($mxs as &$mx) {
948 foreach ($lcl_mxs as $lcl) {
c754cf5b 949 if (fnmatch($mx['host'], $lcl)) {
ccdbc270 950 $broken = $mx['text'];
951 break;
952 }
953 }
954 if ($broken) {
3083bd93 955 $mails[] = array('mail' => $mail->email, 'text' => $broken);
f653ff3d 956 break;
ccdbc270 957 }
958 }
959 }
960 }
961 return $mails;
962 }
e97e9b8f 963
e97e9b8f
VZ
964 public function active_emails()
965 {
966 $emails = array();
967 foreach ($this->emails as $mail) {
968 if ($mail->active) {
969 $emails[] = $mail;
970 }
971 }
972 return $emails;
973 }
45282934 974
45282934
VZ
975 public function get_uid()
976 {
12a587df 977 return $this->user->id();
45282934 978 }
24e8f53b
SJ
979
980 private function update_imap()
981 {
982 // Imaps must bounce if and only if the user has no active redirection.
983 if (!$this->other_active('')) {
984 XDB::execute('UPDATE email_redirect_account
985 SET action = \'imap_and_bounce\'
986 WHERE type = \'imap\' AND uid = {?}',
987 $this->user->id());
988 } else {
989 XDB::execute('UPDATE email_redirect_account
990 SET action = \'let_spams\'
991 WHERE type = \'imap\' AND uid = {?}',
992 $this->user->id());
993 }
994 }
0337d704 995}
996
a7de4ef7 997// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 998?>