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