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