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