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