Improve mailings to subsets
[platal.git] / include / emails.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 $res = XDB::query("SELECT COUNT(*)
33 FROM aliases
34 WHERE id = {?} AND FIND_IN_SET('bestalias', flags) AND type != 'homonyme'",
35 $user->id());
36 if ($res->fetchOneCell()) {
37 return;
38 }
39
40 XDB::execute("UPDATE aliases
41 SET flags=CONCAT(flags,',','bestalias')
42 WHERE id={?} AND type!='homonyme'
43 ORDER BY !FIND_IN_SET('usage',flags),alias LIKE '%.%', LENGTH(alias)
44 LIMIT 1", $user->id());
45 }
46
47 // function valide_email() {{{1
48 // Returns a cleaned-up version of the @p email string. It removes garbage
49 // characters, and determines the canonical form (without _ and +) for
50 // Polytechnique.org email addresses.
51 function valide_email($str)
52 {
53 global $globals;
54
55 $em = trim(rtrim($str));
56 $em = str_replace('<', '', $em);
57 $em = str_replace('>', '', $em);
58 list($ident, $dom) = explode('@', $em);
59 if ($dom == $globals->mail->domain or $dom == $globals->mail->domain2) {
60 list($ident1) = explode('_', $ident);
61 list($ident) = explode('+', $ident1);
62 }
63 return $ident . '@' . $dom;
64 }
65
66 // function isvalid_email_redirection() {{{1
67 /** vérifie si une adresse email convient comme adresse de redirection
68 * @param $email l'adresse email a verifier
69 * @return BOOL
70 */
71 function isvalid_email_redirection($email)
72 {
73 return isvalid_email($email) &&
74 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
75 }
76
77 // function idsFromMails() {{{1
78 /** Converts an array of emails to an array of email => uid
79 * @param $emails : array of emails
80 * @return array of ($email => $uid)
81 */
82 function idsFromMails($emails)
83 {
84 global $globals;
85 $domain_mails = array();
86 $alias_mails = array();
87 $other_mails = array();
88 /* Find type of email address */
89 foreach ($emails as $email) {
90 if (strpos($email, '@') === false) {
91 $user = $email;
92 $domain = $globals->mail->domain2;
93 } else {
94 list($user, $domain) = explode('@', $email);
95 }
96 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
97 list($user) = explode('+', $user);
98 list($user) = explode('_', $user);
99 $alias_mails[$user] = $email;
100 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
101 list($user) = explode('+', $user);
102 list($user) = explode('_', $user);
103 $domain_mails[$user] = $email;
104 } else {
105 $other_mails[] = $email;
106 }
107 }
108 $uids = array();
109 /* domain users */
110 if (count($domain_mails)) {
111 $domain_users = array();
112 foreach (array_keys($domain_mails) as $user) {
113 $domain_users[] = XDB::escape($user);
114 }
115 $list = implode(',', $domain_users);
116 $res = XDB::query("SELECT alias, id
117 FROM aliases
118 WHERE alias IN ($list)");
119 foreach ($res->fetchAllRow() as $row) {
120 list ($alias, $id) = $row;
121 $uids[$domain_mails[$alias]] = $id;
122 }
123 }
124
125 /* Alias users */
126 if (count($alias_mails)) {
127 $alias_users = array();
128 foreach (array_keys($alias_mails) as $user) {
129 $alias_users[] = XDB::escape($user."@".$globals->mail->alias_dom);
130 }
131 $list = implode(',', $alias_users);
132 $res = XDB::query("SELECT v.alias, a.id
133 FROM virtual AS v
134 INNER JOIN virtual_redirect AS r USING(vid)
135 INNER JOIN aliases AS a ON (a.type = 'a_vie'
136 AND r.redirect = CONCAT(a.alias, '@{$globals->mail->domain2}'))
137 WHERE v.alias IN ($list)");
138 foreach ($res->fetchAllRow() as $row) {
139 list ($alias, $id) = $row;
140 $uids[$alias_mails[$alias]] = $id;
141 }
142 }
143
144 /* Other mails */
145 if (count($other_mails)) {
146 $other_users = array();
147 foreach (array_keys($other_mails) as $user) {
148 $other_users[] = XDB::escape($user);
149 }
150 $list = implode(',', $other_users);
151 $res = XDB::query("SELECT email, uid
152 FROM emails
153 WHERE email IN ($list)");
154 foreach ($res->fetchAllRow() as $row) {
155 list ($email, $uid) = $row;
156 $uids[$other_mails[$email]] = $uid;
157 }
158 }
159
160 return $uids;
161 }
162
163 // class Bogo {{{1
164 // The Bogo class represents a spam filtering level in plat/al architecture.
165 class Bogo
166 {
167 // properties {{{2
168
169 private $user;
170 private $state;
171 private $_states = Array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
172
173 // constructor {{{2
174
175 public function __construct(User &$user)
176 {
177 if (!$user) {
178 return;
179 }
180
181 $this->user = &$user;
182 $res = XDB::query('SELECT email FROM emails WHERE uid = {?} AND flags = "filter"', $user->id());
183 if ($res->numRows()) {
184 $this->state = $res->fetchOneCell();
185 } else {
186 $this->state = 'tag_and_drop_spams';
187 $res = XDB::query(
188 "INSERT INTO emails (uid, email, rewrite, panne, flags)
189 VALUES ({?}, 'tag_and_drop_spams', '', '0000-00-00', 'filter')",
190 $user->id());
191 }
192 }
193
194 // public function change() {{{2
195
196 public function change($state)
197 {
198 $this->state = is_int($state) ? $this->_states[$state] : $state;
199 XDB::execute('UPDATE emails SET email = {?} WHERE uid = {?} AND flags = "filter"',
200 $this->state, $this->user->id());
201 }
202
203 // pubic function level() {{{2
204
205 public function level()
206 {
207 return array_search($this->state, $this->_states);
208 }
209 }
210
211 // class Email {{{1
212 // Represents an "email address" used as final recipient for plat/al-managed
213 // addresses; it can be subclasses a Redirection emails (third-party) or as
214 // Storage emails (Polytechnique.org).
215 abstract class Email
216 {
217 protected $user;
218
219 // Basic email properties; $sufficient indicates if the email can be used as
220 // an unique redirection; $email contains the delivery email address.
221 public $type;
222 public $sufficient;
223 public $email;
224 public $display_email;
225
226 // Redirection status properties.
227 public $active;
228 public $broken;
229 public $disabled;
230 public $rewrite;
231 public $allow_rewrite;
232 public $hash;
233
234 // Redirection bounces stats.
235 public $panne;
236 public $last;
237 public $panne_level;
238
239 // Activates the email address as a redirection.
240 public abstract function activate();
241
242 // Deactivates the email address as a redirection.
243 public abstract function deactivate();
244
245 // Sets the rewrite rule for the given address.
246 public abstract function set_rewrite($rewrite);
247
248 // Resets the error counts associated with the redirection.
249 public abstract function clean_errors();
250
251 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
252 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
253 // can be definitively removed; 'disable' indicates if the email has a third
254 // status 'disabled' in addition to 'active' and 'inactive').
255 public abstract function has_rewrite();
256 public abstract function is_removable();
257 public abstract function has_disable();
258 }
259
260 // class EmailRedirection {{{1
261 // Implementation of Email for third-party redirection (redirection of emails to
262 // external user-supplied addresses).
263 class EmailRedirection extends Email
264 {
265 // constructor {{{2
266
267 public function __construct(User &$user, $row)
268 {
269 $this->user = &$user;
270 $this->sufficient = true;
271
272 list($this->email, $flags, $this->rewrite, $this->allow_rewrite, $this->hash, $this->panne, $this->last, $this->panne_level) = $row;
273 $this->display_email = $this->email;
274 $this->active = ($flags == 'active');
275 $this->broken = ($flags == 'panne');
276 $this->disabled = ($flags == 'disable');
277 }
278
279 // public function activate() {{{2
280
281 public function activate()
282 {
283 if (!$this->active) {
284 XDB::execute("UPDATE emails
285 SET panne_level = IF(flags = 'panne', panne_level - 1, panne_level),
286 flags = 'active'
287 WHERE uid = {?} AND email = {?}", $this->user->id(), $this->email);
288 S::logger()->log("email_on", $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ""));
289 $this->active = true;
290 $this->broken = false;
291 }
292 }
293
294 // public function deactivate() {{{2
295
296 public function deactivate()
297 {
298 if ($this->active) {
299 XDB::execute("UPDATE emails SET flags =''
300 WHERE uid = {?} AND email = {?}", $this->user->id(), $this->email);
301 S::logger()->log("email_off", $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
302 $this->active = false;
303 }
304 }
305
306 // public function set_rewrite() {{{2
307
308 public function set_rewrite($rewrite)
309 {
310 if ($this->rewrite == $rewrite) {
311 return;
312 }
313 if (!$rewrite || !isvalid_email($rewrite)) {
314 $rewrite = '';
315 }
316 XDB::execute('UPDATE emails SET rewrite = {?} WHERE uid = {?} AND email = {?}', $rewrite, $this->user->id(), $this->email);
317 $this->rewrite = $rewrite;
318 if (!$this->allow_rewrite) {
319 global $globals;
320 if (empty($this->hash)) {
321 $this->hash = rand_url_id();
322 XDB::execute("UPDATE emails
323 SET hash = {?}
324 WHERE uid = {?} AND email = {?}", $this->hash, $this->user->id(), $this->email);
325 }
326 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
327 $mail->assign('mail', $this);
328 $mail->assign('user', $this->user);
329 $mail->assign('baseurl', $globals->baseurl);
330 $mail->assign('sitename', $globals->core->sitename);
331 $mail->assign('to', $this->email);
332 $mail->send($this->user->isEmailFormatHtml());
333 }
334 return;
335 }
336
337 // public function clean_errors() {{{2
338
339 public function clean_errors()
340 {
341 if (!S::admin()) {
342 return false;
343 }
344 $this->panne = 0;
345 $this->panne_level = 0;
346 $this->last = 0;
347 return XDB::execute("UPDATE emails
348 SET panne_level = 0, panne = 0, last = 0
349 WHERE uid = {?} AND email = {?}",
350 $this->user->id(), $this->email);
351 }
352
353 // public function has_rewrite() {{{2
354
355 public function has_rewrite()
356 {
357 return true;
358 }
359
360 // public function is_removable() {{{2
361
362 public function is_removable()
363 {
364 return true;
365 }
366
367 // public function has_disable() {{{2
368
369 public function has_disable()
370 {
371 return true;
372 }
373 }
374
375 // class EmailStorage {{{1
376 // Implementation of Email for email storage backends from Polytechnique.org.
377 class EmailStorage extends Email
378 {
379 // Shortname to realname mapping for known mail storage backends.
380 private $display_names = array(
381 'imap' => 'Accès de secours aux emails (IMAP)',
382 'googleapps' => 'Compte Google Apps',
383 );
384
385 // Retrieves the current list of actives storages.
386 private function get_storages()
387 {
388 $res = XDB::query("SELECT mail_storage
389 FROM auth_user_md5
390 WHERE user_id = {?}", $this->user->id());
391 return new PlFlagSet($res->fetchOneCell());
392 }
393
394 // Updates the list of active storages.
395 private function set_storages($storages)
396 {
397 XDB::execute("UPDATE auth_user_md5
398 SET mail_storage = {?}
399 WHERE user_id = {?}", $storages, $this->user->id());
400 }
401
402 // Returns the list of allowed storages for the @p user.
403 static public function get_allowed_storages(User &$user)
404 {
405 global $globals;
406 $storages = array();
407
408 // Google Apps storage is available for users with valid Google Apps account.
409 require_once 'googleapps.inc.php';
410 if ($globals->mailstorage->googleapps_domain &&
411 GoogleAppsAccount::account_status($user->id()) == 'active') {
412 $storages[] = 'googleapps';
413 }
414
415 // IMAP storage is always visible to administrators, and is allowed for
416 // everyone when the service is marked as 'active'.
417 if ($globals->mailstorage->imap_active || S::admin()) {
418 $storages[] = 'imap';
419 }
420
421 return $storages;
422 }
423
424
425 public function __construct(User &$user, $name)
426 {
427 $this->user = &$user;
428 $this->email = $name;
429 $this->display_email = (isset($this->display_names[$name]) ? $this->display_names[$name] : $name);
430
431 $storages = $this->get_storages();
432 $this->sufficient = ($name == 'googleapps');
433 $this->active = $storages->hasFlag($name);
434 $this->broken = false;
435 $this->disabled = false;
436 $this->rewrite = '';
437 $this->panne = $this->last = $this->panne_level = 0;
438 }
439
440 public function activate()
441 {
442 if (!$this->active) {
443 $storages = $this->get_storages();
444 $storages->addFlag($this->email);
445 $this->set_storages($storages);
446 $this->active = true;
447 }
448 }
449
450 public function deactivate()
451 {
452 if ($this->active) {
453 $storages = $this->get_storages();
454 $storages->rmFlag($this->email);
455 $this->set_storages($storages);
456 $this->active = false;
457 }
458
459 }
460
461 // Source rewrite can't be enabled for email storage addresses.
462 public function set_rewrite($rewrite) {}
463
464 // Email storage are not supposed to be broken, hence not supposed to be
465 // cleaned-up.
466 public function clean_errors() {}
467
468 // Capabilities.
469 public function has_rewrite() { return false; }
470 public function is_removable() { return false; }
471 public function has_disable() { return false; }
472 }
473
474 // class Redirect {{{1
475 // Redirect is a placeholder class for an user's active redirections (third-party
476 // redirection email, or Polytechnique.org mail storages).
477 class Redirect
478 {
479 // properties {{{2
480
481 private $flag_active = 'active';
482 private $user;
483
484 public $emails;
485 public $bogo;
486
487 // constructor {{{2
488
489 public function __construct(User &$user)
490 {
491 $this->user = &$user;
492 $this->bogo = new Bogo($user);
493
494 // Adds third-party email redirections.
495 $res = XDB::iterRow("SELECT email, flags, rewrite, allow_rewrite, hash, panne, last, panne_level
496 FROM emails
497 WHERE uid = {?} AND flags != 'filter'", $user->id());
498 $this->emails = Array();
499 while ($row = $res->next()) {
500 $this->emails[] = new EmailRedirection($user, $row);
501 }
502
503 // Adds local email storage backends.
504 foreach (EmailStorage::get_allowed_storages($user) as $storage) {
505 $this->emails[] = new EmailStorage($user, $storage);
506 }
507 }
508
509 // public function other_active() {{{2
510
511 public function other_active($email)
512 {
513 foreach ($this->emails as $mail) {
514 if ($mail->email != $email && $mail->active && $mail->sufficient) {
515 return true;
516 }
517 }
518 return false;
519 }
520
521 // public function delete_email() {{{2
522
523 public function delete_email($email)
524 {
525 if (!$this->other_active($email)) {
526 return ERROR_INACTIVE_REDIRECTION;
527 }
528 XDB::execute('DELETE FROM emails WHERE uid = {?} AND email = {?}', $this->user->id(), $email);
529 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
530 foreach ($this->emails as $i => $mail) {
531 if ($email == $mail->email) {
532 unset($this->emails[$i]);
533 }
534 }
535 check_redirect($this);
536 return SUCCESS;
537 }
538
539 // public function add_email() {{{2
540
541 public function add_email($email)
542 {
543 $email_stripped = strtolower(trim($email));
544 if (!isvalid_email($email_stripped)) {
545 return ERROR_INVALID_EMAIL;
546 }
547 if (!isvalid_email_redirection($email_stripped)) {
548 return ERROR_LOOP_EMAIL;
549 }
550 XDB::execute('REPLACE INTO emails (uid,email,flags) VALUES({?},{?},"active")', $this->user->id(), $email);
551 if ($logger = S::v('log', null)) { // may be absent --> step4.php
552 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
553 }
554 foreach ($this->emails as $mail) {
555 if ($mail->email == $email_stripped) {
556 return SUCCESS;
557 }
558 }
559 $this->emails[] = new EmailRedirection($this->user, array($email, 'active', '', 0, null, '0000-00-00', '0000-00-00', 0));
560
561 // security stuff
562 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
563 check_redirect($this);
564 return SUCCESS;
565 }
566
567 // public function modify_email() {{{2
568
569 public function modify_email($emails_actifs, $emails_rewrite)
570 {
571 foreach ($this->emails as &$mail) {
572 if (in_array($mail->email, $emails_actifs)) {
573 $mail->activate();
574 } else {
575 $mail->deactivate();
576 }
577 $mail->set_rewrite($emails_rewrite[$mail->email]);
578 }
579 check_redirect($this);
580 }
581
582 // public function modify_one_email() {{{2
583
584 public function modify_one_email($email, $activate)
585 {
586 $allinactive = true;
587 $thisone = false;
588 foreach ($this->emails as $i=>$mail) {
589 if ($mail->email == $email) {
590 $thisone = $i;
591 }
592 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
593 }
594 if ($thisone === false) {
595 return ERROR_INVALID_EMAIL;
596 }
597 if ($allinactive || $activate) {
598 $this->emails[$thisone]->activate();
599 } else {
600 $this->emails[$thisone]->deactivate();
601 }
602 check_redirect($this);
603 if ($allinactive && !$activate) {
604 return ERROR_INACTIVE_REDIRECTION;
605 } else {
606 return SUCCESS;
607 }
608 }
609
610 // public function modify_one_email_redirect() {{{2
611
612 public function modify_one_email_redirect($email, $redirect)
613 {
614 foreach ($this->emails as &$mail) {
615 if ($mail->email == $email) {
616 $mail->set_rewrite($redirect);
617 check_redirect($this);
618 return;
619 }
620 }
621 }
622
623 // function clean_errors() {{{2
624
625 public function clean_errors($email)
626 {
627 foreach ($this->emails as &$mail) {
628 if ($mail->email == $email) {
629 check_redirect($this);
630 return $mail->clean_errors();
631 }
632 }
633 return false;
634 }
635
636 // function disable() {{{2
637
638 public function disable()
639 {
640 XDB::execute("UPDATE emails
641 SET flags = 'disable'
642 WHERE flags = 'active' AND uid = {?}", $this->user->id());
643 foreach ($this->emails as &$mail) {
644 if ($mail->active && $mail->has_disable()) {
645 $mail->disabled = true;
646 $mail->active = false;
647 }
648 }
649 check_redirect($this);
650 }
651
652 // function enable() {{{2
653
654 public function enable()
655 {
656 XDB::execute("UPDATE emails
657 SET flags = 'active'
658 WHERE flags = 'disable' AND uid = {?}", $this->user->id());
659 foreach ($this->emails as &$mail) {
660 if ($mail->disabled) {
661 $mail->active = true;
662 $mail->disabled = false;
663 }
664 check_redirect($this);
665 }
666 }
667
668 // function get_broken_mx() {{{2
669
670 public function get_broken_mx()
671 {
672 $res = XDB::query("SELECT host, text
673 FROM mx_watch
674 WHERE state != 'ok'");
675 if (!$res->numRows()) {
676 return array();
677 }
678 $mxs = $res->fetchAllAssoc();
679 $mails = array();
680 foreach ($this->emails as &$mail) {
681 if ($mail->active && strstr($mail->email, '@') !== false) {
682 list(,$domain) = explode('@', $mail->email);
683 getmxrr($domain, $lcl_mxs);
684 if (empty($lcl_mxs)) {
685 $lcl_mxs = array($domain);
686 }
687 $broken = false;
688 foreach ($mxs as &$mx) {
689 foreach ($lcl_mxs as $lcl) {
690 if (fnmatch($mx['host'], $lcl)) {
691 $broken = $mx['text'];
692 break;
693 }
694 }
695 if ($broken) {
696 $mails[] = array('mail' => $mail->email, 'text' => $broken);
697 break;
698 }
699 }
700 }
701 }
702 return $mails;
703 }
704
705 // function active_emails() {{{2
706
707 public function active_emails()
708 {
709 $emails = array();
710 foreach ($this->emails as $mail) {
711 if ($mail->active) {
712 $emails[] = $mail;
713 }
714 }
715 return $emails;
716 }
717
718 // function get_uid() {{{2
719
720 public function get_uid()
721 {
722 return $this->user->id();
723 }
724 }
725
726 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
727 ?>