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