Adapts email related user defined parameters to the new mail chain.
[platal.git] / include / emails.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 define('SUCCESS', 1);
23 define('ERROR_INACTIVE_REDIRECTION', 2);
24 define('ERROR_INVALID_EMAIL', 3);
25 define('ERROR_LOOP_EMAIL', 4);
26
27 // function fix_bestalias() {{{1
28 // Checks for an existing 'bestalias' among the the current user's aliases, and
29 // eventually selects a new bestalias when required.
30 function fix_bestalias(User $user)
31 {
32 $count = XDB::fetchOneCell('SELECT COUNT(*)
33 FROM email_source_account
34 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags)',
35 $user->id());
36
37 if ($count == 1) {
38 return;
39 } elseif ($count > 1) {
40 // If too many bestaliases, delete the bestalias flag from all this
41 // user's emails (this should never happen).
42 XDB::execute("UPDATE email_source_account
43 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
44 WHERE uid = {?}",
45 $user->id());
46 }
47
48 // If no bestalias is selected, we choose the shortest email which is not
49 // related to a usage name and contains a '.'.
50 XDB::execute("UPDATE email_source_account
51 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
52 WHERE uid = {?}
53 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
54 LIMIT 1",
55 $user->id());
56 }
57
58 // function valide_email() {{{1
59 // Returns a cleaned-up version of the @p email string. It removes garbage
60 // characters, and determines the canonical form (without _ and +) for
61 // Polytechnique.org email addresses.
62 function valide_email($str)
63 {
64 global $globals;
65
66 $em = trim(rtrim($str));
67 $em = str_replace('<', '', $em);
68 $em = str_replace('>', '', $em);
69 if (strpos($em, '@') === false) {
70 return;
71 }
72 list($ident, $dom) = explode('@', $em);
73 if ($dom == $globals->mail->domain || $dom == $globals->mail->domain2) {
74 list($ident1) = explode('_', $ident);
75 list($ident) = explode('+', $ident1);
76 }
77 return $ident . '@' . $dom;
78 }
79
80 // function isvalid_email_redirection() {{{1
81 /** Checks if an email is a suitable redirection.
82 * @param $email the email to check
83 * @return BOOL
84 */
85 function isvalid_email_redirection($email)
86 {
87 return isvalid_email($email) &&
88 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
89 }
90
91 // function ids_from_mails() {{{1
92 // Converts an array of emails to an array of email => uid, where email is the
93 // given email when we found a matching user.
94 function ids_from_mails(array $emails)
95 {
96 global $globals;
97
98 // Removes duplicates, if any.
99 $emails = array_unique($emails);
100
101 // Formats and splits by domain type (locally managed or external) emails.
102 $domain_emails = array();
103 $other_emails = array();
104 foreach ($emails as $email) {
105 if (strpos($email, '@') === false) {
106 $user = $email;
107 $domain = $globals->mail->domain2;
108 } else {
109 list($user, $domain) = explode('@', $email);
110 }
111 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2
112 || $domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
113 list($user) = explode('+', $user);
114 list($user) = explode('_', $user);
115 $domain_emails[$email] = strtolower($user . '@' . $domain);
116 } else {
117 $other_emails[$email] = strtolower($user . '@' . $domain);
118 }
119 }
120
121 // Retrieves emails from our domains.
122 $domain_uids = XDB::fetchAllAssoc('email',
123 'SELECT email, uid
124 FROM email_source_account
125 WHERE email IN {?}',
126 array_unique($domain_emails));
127
128 // Retrieves emails from redirections.
129 $other_uids = XDB::fetchAllAssoc('redirect',
130 'SELECT redirect, uid
131 FROM email_redirect_account
132 WHERE redirect IN {?}',
133 array_unique($other_emails));
134
135 // Associates given emails with the corresponding uid.
136 $uids = array();
137 foreach (array_merge($domain_emails, $other_emails) as $email => $canonical_email) {
138 if (array_key_exists($canonical_email, $domain_uids)) {
139 $uids[$email] = $domain_uids[$canonical_email];
140 } elseif (array_key_exists($canonical_email, $other_uids)) {
141 $uids[$email] = $other_uids[$canonical_email];
142 }
143 }
144
145 return $uids;
146 }
147
148 // class Bogo {{{1
149 // The Bogo class represents a spam filtering level in plat/al architecture.
150 class Bogo
151 {
152 private static $states = array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
153
154 private $user;
155 private $state;
156
157 public function __construct(User $user)
158 {
159 if (!$user) {
160 return;
161 }
162
163 $this->user = &$user;
164 $res = XDB::query('SELECT action
165 FROM email_redirect_account
166 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
167 $user->id());
168 if ($res->numRows() == 0) {
169 return;
170 }
171 $this->state = $res->fetchOneCell();
172 }
173
174 public function change($state)
175 {
176 $this->state = is_int($state) ? self::$states[$state] : $state;
177 XDB::execute('UPDATE email_redirect_account
178 SET action = {?}
179 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
180 $this->state, $this->user->id());
181 }
182
183 public function level()
184 {
185 return array_search($this->state, self::$states);
186 }
187 }
188
189 // class Email {{{1
190 // Represents an "email address" used as final recipient for plat/al-managed
191 // addresses.
192 class Email
193 {
194 // Lists fields to load automatically.
195 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
196
197 // Shortname to realname mapping for known mail storage backends.
198 static private $display_names = array(
199 'imap' => 'Accès de secours aux emails (IMAP)',
200 'googleapps' => 'Compte Google Apps',
201 );
202 static private $storage_domains = array(
203 'imap' => 'imap',
204 'googleapps' => 'g'
205 );
206
207 private $user;
208
209 // Basic email properties; $sufficient indicates if the email can be used as
210 // an unique redirection; $redirect contains the delivery email address.
211 public $type;
212 public $sufficient;
213 public $email;
214 public $display_email;
215 public $domain;
216 public $action;
217
218 // Redirection status properties.
219 public $active;
220 public $inactive;
221 public $broken;
222 public $disabled;
223 public $rewrite;
224 public $allow_rewrite;
225 public $hash;
226
227 // Redirection bounces stats.
228 public $last;
229 public $broken_level;
230 public $broken_date;
231
232 public function __construct(User $user, array $row)
233 {
234 foreach (self::$field_names as $field) {
235 if (array_key_exists($field, $row)) {
236 $this->$field = $row[$field];
237 }
238 }
239 $this->email = $row['redirect'];
240
241 if (array_key_exists($this->type, Email::$display_names)) {
242 $this->display_email = self::$display_names[$this->type];
243 } else {
244 $this->display_email = $this->email;
245 }
246 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
247 $this->$status = ($status == $row['flags']);
248 }
249 $this->sufficient = ($this->type == 'smtp' || $this->type == 'googleapps');
250 $this->user = &$user;
251 }
252
253 // Activates the email address as a redirection.
254 public function activate()
255 {
256 if ($this->inactive) {
257 XDB::execute('UPDATE email_redirect_account
258 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
259 WHERE uid = {?} AND redirect = {?}',
260 $this->user->id(), $this->email);
261 S::logger()->log('email_on', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ''));
262 $this->inactive = false;
263 $this->active = true;
264 }
265 }
266
267 // Deactivates the email address as a redirection.
268 public function deactivate()
269 {
270 if ($this->active) {
271 XDB::execute('UPDATE email_redirect_account
272 SET flags = \'inactive\'
273 WHERE uid = {?} AND redirect = {?}',
274 $this->user->id(), $this->email);
275 S::logger()->log('email_off', $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
276 $this->inactive = true;
277 $this->active = false;
278 }
279 }
280
281
282 // Sets the rewrite rule for the given address.
283 public function set_rewrite($rewrite)
284 {
285 if ($this->type != 'smtp' || $this->rewrite == $rewrite) {
286 return;
287 }
288 if (!$rewrite || !isvalid_email($rewrite)) {
289 $rewrite = '';
290 }
291 XDB::execute('UPDATE email_redirect_account
292 SET rewrite = {?}
293 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
294 $rewrite, $this->user->id(), $this->email);
295 $this->rewrite = $rewrite;
296 if (!$this->allow_rewrite) {
297 global $globals;
298 if (empty($this->hash)) {
299 $this->hash = rand_url_id();
300 XDB::execute('UPDATE email_redirect_account
301 SET hash = {?}
302 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
303 $this->hash, $this->user->id(), $this->email);
304 }
305 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
306 $mail->assign('mail', $this);
307 $mail->assign('user', $this->user);
308 $mail->assign('baseurl', $globals->baseurl);
309 $mail->assign('sitename', $globals->core->sitename);
310 $mail->assign('to', $this->email);
311 $mail->send($this->user->isEmailFormatHtml());
312 }
313 }
314
315
316 // Resets the error counts associated with the redirection.
317 public function clean_errors()
318 {
319 if ($this->type != 'smtp') {
320 return;
321 }
322 if (!S::admin()) {
323 return false;
324 }
325 $this->broken = 0;
326 $this->broken_level = 0;
327 $this->last = 0;
328 return XDB::execute('UPDATE email_redirect_account
329 SET broken_level = 0, broken_date = 0, last = 0
330 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
331 $this->user->id(), $this->email);
332 }
333
334
335 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
336 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
337 // can be definitively removed; 'disable' indicates if the email has a third
338 // status 'disabled' in addition to 'active' and 'inactive').
339 public function has_rewrite()
340 {
341 return ($this->type == 'smtp');
342 }
343
344 public function is_removable()
345 {
346 return ($this->type == 'smtp');
347 }
348
349 public function has_disable()
350 {
351 return true;
352 }
353
354 public function is_redirection()
355 {
356 return ($this->type == 'smtp');
357 }
358
359 // Returns the list of allowed storages for the @p user.
360 static private function get_allowed_storages(User $user)
361 {
362 global $globals;
363 $storages = array();
364
365 // Google Apps storage is available for users with valid Google Apps account.
366 require_once 'googleapps.inc.php';
367 if ($globals->mailstorage->googleapps_domain &&
368 GoogleAppsAccount::account_status($user->id()) == 'active') {
369 $storages[] = 'googleapps';
370 }
371
372 // IMAP storage is always visible to administrators, and is allowed for
373 // everyone when the service is marked as 'active'.
374 if ($globals->mailstorage->imap_active || S::admin()) {
375 $storages[] = 'imap';
376 }
377
378 return $storages;
379 }
380
381 static public function activate_storage(User $user, $storage)
382 {
383 Platal::assert(in_array($storage, self::get_allowed_storages($user)));
384
385 if (!self::is_active_storage($user, $storage)) {
386 global $globals;
387
388 XDB::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
389 VALUES ({?}, {?}, {?}, \'active\')',
390 $user->id(), $storage,
391 $user->hruid . '@' . self::$storage_domains[$storage] . '.' . $globals->mail->domain);
392 }
393 }
394
395 static public function deactivate_storage(User $user, $storage)
396 {
397 if (in_array($storage, self::$storage_domains)) {
398 XDB::execute('DELETE FROM email_redirect_account
399 WHERE uid = {?} AND type = {?}',
400 $user->id(), $storage);
401 }
402 }
403
404 static public function is_active_storage(User $user, $storage)
405 {
406 if (!in_array($storage, self::$storage_domains)) {
407 return false;
408 }
409 $res = XDB::fetchOneCell('SELECT COUNT(*)
410 FROM email_redirect_account
411 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
412 $user->id(), $storage);
413 return !is_null($res) && $res > 0;
414 }
415 }
416 // class Redirect {{{1
417 // Redirect is a placeholder class for an user's active redirections (third-party
418 // redirection email, or Polytechnique.org mail storages).
419 class Redirect
420 {
421 private $flags = 'active';
422 private $user;
423
424 public $emails;
425 public $bogo;
426
427 public function __construct(User $user)
428 {
429 $this->user = &$user;
430 $this->bogo = new Bogo($user);
431
432 // Adds third-party email redirections.
433 $res = XDB::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
434 FROM email_redirect_account
435 WHERE uid = {?} AND type != \'homonym\'',
436 $user->id());
437 $this->emails = array();
438 while ($row = $res->next()) {
439 $this->emails[] = new Email($user, $row);
440 }
441 }
442
443 public function other_active($email)
444 {
445 foreach ($this->emails as $mail) {
446 if ($mail->email != $email && $mail->active && $mail->sufficient) {
447 return true;
448 }
449 }
450 return false;
451 }
452
453 public function delete_email($email)
454 {
455 if (!$this->other_active($email)) {
456 return ERROR_INACTIVE_REDIRECTION;
457 }
458 XDB::execute('DELETE FROM email_redirect_account
459 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
460 $this->user->id(), $email);
461 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
462 foreach ($this->emails as $i => $mail) {
463 if ($email == $mail->email) {
464 unset($this->emails[$i]);
465 }
466 }
467 check_redirect($this);
468 return SUCCESS;
469 }
470
471 public function add_email($email)
472 {
473 $email_stripped = strtolower(trim($email));
474 if (!isvalid_email($email_stripped)) {
475 return ERROR_INVALID_EMAIL;
476 }
477 if (!isvalid_email_redirection($email_stripped)) {
478 return ERROR_LOOP_EMAIL;
479 }
480 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
481 XDB::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
482 VALUES ({?}, {?}, \'active\')',
483 $this->user->id(), $email);
484 if ($logger = S::v('log', null)) { // may be absent --> step4.php
485 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
486 }
487 foreach ($this->emails as $mail) {
488 if ($mail->email == $email_stripped) {
489 return SUCCESS;
490 }
491 }
492 $this->emails[] = new Email($this->user, array(
493 'redirect' => $email,
494 'rewrite' => '',
495 'type' => 'smtp',
496 'action' => 'default',
497 'broken_date' => '0000-00-00',
498 'broken_level' => 0,
499 'last' => '0000-00-00',
500 'flags' => 'active',
501 'hash' => null,
502 'allow_rewrite' => 0
503 ));
504
505 // security stuff
506 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
507 check_redirect($this);
508 return SUCCESS;
509 }
510
511 public function modify_email($emails_actifs, $emails_rewrite)
512 {
513 foreach ($this->emails as &$email) {
514 if (in_array($email->email, $emails_actifs)) {
515 $email->activate();
516 } else {
517 $email->deactivate();
518 }
519 $email->set_rewrite($emails_rewrite[$email->email]);
520 }
521 check_redirect($this);
522 return SUCCESS;
523 }
524
525 public function modify_one_email($email, $activate)
526 {
527 $allinactive = true;
528 $thisone = false;
529 foreach ($this->emails as $i=>$mail) {
530 if ($mail->email == $email) {
531 $thisone = $i;
532 }
533 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
534 }
535 if ($thisone === false) {
536 return ERROR_INVALID_EMAIL;
537 }
538 if ($allinactive || $activate) {
539 $this->emails[$thisone]->activate();
540 } else {
541 $this->emails[$thisone]->deactivate();
542 }
543 check_redirect($this);
544 if ($allinactive && !$activate) {
545 return ERROR_INACTIVE_REDIRECTION;
546 }
547 return SUCCESS;
548 }
549
550 public function modify_one_email_redirect($email, $redirect)
551 {
552 foreach ($this->emails as &$mail) {
553 if ($mail->email == $email) {
554 $mail->set_rewrite($redirect);
555 check_redirect($this);
556 return;
557 }
558 }
559 }
560
561 public function clean_errors($email)
562 {
563 foreach ($this->emails as &$mail) {
564 if ($mail->email == $email) {
565 check_redirect($this);
566 return $mail->clean_errors();
567 }
568 }
569 return false;
570 }
571
572 public function disable()
573 {
574 XDB::execute("UPDATE email_redirect_account
575 SET flags = 'disable'
576 WHERE flags = 'active' AND uid = {?}", $this->user->id());
577 foreach ($this->emails as &$mail) {
578 if ($mail->active && $mail->has_disable()) {
579 $mail->disabled = true;
580 $mail->active = false;
581 }
582 }
583 check_redirect($this);
584 }
585
586 public function enable()
587 {
588 XDB::execute("UPDATE email_redirect_account
589 SET flags = 'active'
590 WHERE flags = 'disable' AND uid = {?}", $this->user->id());
591 foreach ($this->emails as &$mail) {
592 if ($mail->disabled) {
593 $mail->disabled = false;
594 $mail->active = true;
595 }
596 check_redirect($this);
597 }
598 }
599
600 public function get_broken_mx()
601 {
602 $res = XDB::query("SELECT host, text
603 FROM mx_watch
604 WHERE state != 'ok'");
605 if (!$res->numRows()) {
606 return array();
607 }
608 $mxs = $res->fetchAllAssoc();
609 $mails = array();
610 foreach ($this->emails as &$mail) {
611 if ($mail->active && strstr($mail->email, '@') !== false) {
612 list(,$domain) = explode('@', $mail->email);
613 getmxrr($domain, $lcl_mxs);
614 if (empty($lcl_mxs)) {
615 $lcl_mxs = array($domain);
616 }
617 $broken = false;
618 foreach ($mxs as &$mx) {
619 foreach ($lcl_mxs as $lcl) {
620 if (fnmatch($mx['host'], $lcl)) {
621 $broken = $mx['text'];
622 break;
623 }
624 }
625 if ($broken) {
626 $mails[] = array('mail' => $mail->email, 'text' => $broken);
627 break;
628 }
629 }
630 }
631 }
632 return $mails;
633 }
634
635 public function active_emails()
636 {
637 $emails = array();
638 foreach ($this->emails as $mail) {
639 if ($mail->active) {
640 $emails[] = $mail;
641 }
642 }
643 return $emails;
644 }
645
646 public function get_uid()
647 {
648 return $this->user->id();
649 }
650 }
651
652 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
653 ?>