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