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