Merge branch 'platal-0.9.17'
[platal.git] / include / emails.inc.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 Polytechnique.org *
0337d704 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
0337d704 22define("SUCCESS", 1);
23define("ERROR_INACTIVE_REDIRECTION", 2);
24define("ERROR_INVALID_EMAIL", 3);
25define("ERROR_LOOP_EMAIL", 4);
26
441c2451 27// function fix_bestalias() {{{1
11ed26e5
VZ
28// Checks for an existing 'bestalias' among the the current user's aliases, and
29// eventually selects a new bestalias when required.
0337d704 30function fix_bestalias($uid)
31{
11ed26e5
VZ
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()) {
0337d704 37 return;
38 }
11ed26e5 39
08cce2ff 40 XDB::execute("UPDATE aliases
612a2d8a 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);
0337d704 45}
46
441c2451 47// function valide_email() {{{1
11ed26e5
VZ
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.
0337d704 51function valide_email($str)
52{
a3a049fc 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;
0337d704 64}
65
c6310567
FB
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 */
71function isvalid_email_redirection($email)
72{
73 return isvalid_email($email) &&
74 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
75}
76
441c2451 77// class Bogo {{{1
11ed26e5 78// The Bogo class represents a spam filtering level in plat/al architecture.
0337d704 79class Bogo
80{
441c2451 81 // properties {{{2
a3a049fc 82
11ed26e5 83 private $uid;
612a2d8a 84 private $state;
85 private $_states = Array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
0337d704 86
441c2451 87 // constructor {{{2
a3a049fc 88
612a2d8a 89 public function __construct($uid)
0337d704 90 {
3c1e6a1e 91 if (!$uid) {
92 return;
93 }
11ed26e5
VZ
94
95 $this->uid = $uid;
3c1e6a1e 96 $res = XDB::query('SELECT email FROM emails WHERE uid={?} AND flags="filter"', $uid);
97 if ($res->numRows()) {
612a2d8a 98 $this->state = $res->fetchOneCell();
3c1e6a1e 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 }
0337d704 104 }
105
441c2451 106 // public function change() {{{2
0337d704 107
11ed26e5 108 public function change($state)
0337d704 109 {
612a2d8a 110 $this->state = is_int($state) ? $this->_states[$state] : $state;
111 XDB::execute('UPDATE emails SET email={?} WHERE uid={?} AND flags = "filter"',
11ed26e5 112 $this->state, $this->uid);
0337d704 113 }
114
441c2451 115 // pubic function level() {{{2
0337d704 116
612a2d8a 117 public function level()
118 {
119 return array_search($this->state, $this->_states);
120 }
0337d704 121}
122
441c2451 123// class Email {{{1
11ed26e5
VZ
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).
127abstract class Email
0337d704 128{
11ed26e5 129 protected $uid;
612a2d8a 130
11ed26e5
VZ
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;
612a2d8a 135 public $email;
11ed26e5
VZ
136 public $display_email;
137
138 // Redirection status properties.
612a2d8a 139 public $active;
140 public $broken;
441c2451 141 public $disabled;
612a2d8a 142 public $rewrite;
3d17e48f
FB
143 public $allow_rewrite;
144 public $hash;
11ed26e5
VZ
145
146 // Redirection bounces stats.
612a2d8a 147 public $panne;
148 public $last;
149 public $panne_level;
0337d704 150
11ed26e5
VZ
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).
175class EmailRedirection extends Email
176{
441c2451 177 // constructor {{{2
0337d704 178
11ed26e5 179 public function __construct($uid, $row)
0337d704 180 {
11ed26e5
VZ
181 $this->uid = $uid;
182 $this->sufficient = true;
183
3d17e48f 184 list($this->email, $flags, $this->rewrite, $this->allow_rewrite, $this->hash, $this->panne, $this->last, $this->panne_level) = $row;
11ed26e5 185 $this->display_email = $this->email;
441c2451 186 $this->active = ($flags == 'active');
187 $this->broken = ($flags == 'panne');
188 $this->disabled = ($flags == 'disable');
0337d704 189 }
190
441c2451 191 // public function activate() {{{2
0337d704 192
11ed26e5 193 public function activate()
0337d704 194 {
0337d704 195 if (!$this->active) {
dc557110 196 XDB::execute("UPDATE emails
197 SET panne_level = IF(flags = 'panne', panne_level - 1, panne_level),
198 flags = 'active'
11ed26e5 199 WHERE uid={?} AND email={?}", $this->uid, $this->email);
732e5855 200 S::logger()->log("email_on", $this->email.($this->uid!=S::v('uid') ? "(admin on {$this->uid})" : ""));
0337d704 201 $this->active = true;
dc557110 202 $this->broken = false;
0337d704 203 }
204 }
205
441c2451 206 // public function deactivate() {{{2
0337d704 207
11ed26e5 208 public function deactivate()
0337d704 209 {
0337d704 210 if ($this->active) {
08cce2ff 211 XDB::execute("UPDATE emails SET flags =''
11ed26e5 212 WHERE uid={?} AND email={?}", $this->uid, $this->email);
732e5855 213 S::logger()->log("email_off",$this->email.($this->uid != S::v('uid') ? "(admin on {$this->uid})" : "") );
0337d704 214 $this->active = false;
215 }
216 }
612a2d8a 217
11ed26e5 218 // public function set_rewrite() {{{2
0337d704 219
11ed26e5 220 public function set_rewrite($rewrite)
0337d704 221 {
11ed26e5 222 if ($this->rewrite == $rewrite) {
0337d704 223 return;
224 }
11ed26e5
VZ
225 if (!$rewrite || !isvalid_email($rewrite)) {
226 $rewrite = '';
12acff5d 227 }
11ed26e5
VZ
228 XDB::execute('UPDATE emails SET rewrite={?} WHERE uid={?} AND email={?}', $rewrite, $this->uid, $this->email);
229 $this->rewrite = $rewrite;
3d17e48f
FB
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);
c66de9a0
FB
253 $mail->assign('sitename', $globals->core->sitename);
254 $mail->assign('to', $this->email);
3d17e48f
FB
255 $mail->send($fmt == 'html');
256 }
3c1e6a1e 257 return;
0337d704 258 }
259
11ed26e5 260 // public function clean_errors() {{{2
441c2451 261
11ed26e5 262 public function clean_errors()
441c2451 263 {
264 if (!S::has_perms()) {
265 return false;
266 }
267 $this->panne = 0;
268 $this->panne_level = 0;
269 $this->last = 0;
270 return XDB::execute("UPDATE emails
271 SET panne_level = 0, panne = 0, last = 0
272 WHERE uid = {?} AND email = {?}",
11ed26e5
VZ
273 $this->uid, $this->email);
274 }
275
276 // public function has_rewrite() {{{2
277
278 public function has_rewrite()
279 {
280 return true;
281 }
282
283 // public function is_removable() {{{2
284
285 public function is_removable()
286 {
287 return true;
288 }
289
290 // public function has_disable() {{{2
291
292 public function has_disable()
293 {
294 return true;
441c2451 295 }
0337d704 296}
297
afde0a3a
VZ
298// class EmailStorage {{{1
299// Implementation of Email for email storage backends from Polytechnique.org.
300class EmailStorage extends Email
301{
302 // Shortname to realname mapping for known mail storage backends.
303 private $display_names = array(
304 'imap' => 'Accès de secours aux emails (IMAP)',
690c8519 305 'googleapps' => 'Compte Google Apps',
afde0a3a
VZ
306 );
307
308 // Retrieves the current list of actives storages.
309 private function get_storages()
310 {
311 $res = XDB::query("SELECT mail_storage
312 FROM auth_user_md5
313 WHERE user_id = {?}", $this->uid);
113f6de8 314 return new PlFlagSet($res->fetchOneCell());
afde0a3a
VZ
315 }
316
317 // Updates the list of active storages.
318 private function set_storages($storages)
319 {
320 XDB::execute("UPDATE auth_user_md5
321 SET mail_storage = {?}
77e786e1 322 WHERE user_id = {?}", $storages, $this->uid);
afde0a3a
VZ
323 }
324
325 // Returns the list of allowed storages for the @p user.
326 static public function get_allowed_storages($uid)
327 {
328 global $globals;
329 $storages = array();
330
331 // Google Apps storage is available for users with valid Google Apps account.
332 require_once 'googleapps.inc.php';
333 if ($globals->mailstorage->googleapps_domain &&
334 GoogleAppsAccount::account_status($uid) == 'active') {
335 $storages[] = 'googleapps';
336 }
337
338 // IMAP storage is always visible to administrators, and is allowed for
339 // everyone when the service is marked as 'active'.
340 if ($globals->mailstorage->imap_active || S::has_perms()) {
341 $storages[] = 'imap';
342 }
343
344 return $storages;
345 }
346
347
348 public function __construct($uid, $name)
349 {
350 $this->uid = $uid;
351 $this->email = $name;
352 $this->display_email = (isset($this->display_names[$name]) ? $this->display_names[$name] : $name);
353
354 $storages = $this->get_storages();
355 $this->sufficient = ($name == 'googleapps');
356 $this->active = $storages->hasFlag($name);
357 $this->broken = false;
358 $this->disabled = false;
359 $this->rewrite = '';
360 $this->panne = $this->last = $this->panne_level = 0;
361 }
362
363 public function activate()
364 {
365 if (!$this->active) {
366 $storages = $this->get_storages();
367 $storages->addFlag($this->email);
368 $this->set_storages($storages);
369 $this->active = true;
370 }
371 }
372
373 public function deactivate()
374 {
375 if ($this->active) {
376 $storages = $this->get_storages();
377 $storages->rmFlag($this->email);
378 $this->set_storages($storages);
379 $this->active = false;
380 }
381
382 }
383
384 // Source rewrite can't be enabled for email storage addresses.
385 public function set_rewrite($rewrite) {}
386
387 // Email storage are not supposed to be broken, hence not supposed to be
388 // cleaned-up.
389 public function clean_errors() {}
390
391 // Capabilities.
392 public function has_rewrite() { return false; }
393 public function is_removable() { return false; }
394 public function has_disable() { return false; }
395}
396
441c2451 397// class Redirect {{{1
11ed26e5
VZ
398// Redirect is a placeholder class for an user's active redirections (third-party
399// redirection email, or Polytechnique.org mail storages).
0337d704 400class Redirect
401{
441c2451 402 // properties {{{2
612a2d8a 403
404 private $flag_active = 'active';
405 private $uid;
406
407 public $emails;
408 public $bogo;
0337d704 409
441c2451 410 // constructor {{{2
0337d704 411
612a2d8a 412 public function __construct($_uid)
0337d704 413 {
11ed26e5 414 $this->uid = $_uid;
afde0a3a 415 $this->bogo = new Bogo($_uid);
11ed26e5 416
afde0a3a 417 // Adds third-party email redirections.
3d17e48f 418 $res = XDB::iterRow("SELECT email, flags, rewrite, allow_rewrite, hash, panne, last, panne_level
612a2d8a 419 FROM emails
420 WHERE uid = {?} AND flags != 'filter'", $_uid);
11ed26e5 421 $this->emails = Array();
0337d704 422 while ($row = $res->next()) {
11ed26e5 423 $this->emails[] = new EmailRedirection($_uid, $row);
0337d704 424 }
afde0a3a
VZ
425
426 // Adds local email storage backends.
427 foreach (EmailStorage::get_allowed_storages($_uid) as $storage) {
428 $this->emails[] = new EmailStorage($_uid, $storage);
429 }
0337d704 430 }
431
441c2451 432 // public function other_active() {{{2
0337d704 433
612a2d8a 434 public function other_active($email)
0337d704 435 {
436 foreach ($this->emails as $mail) {
11ed26e5 437 if ($mail->email != $email && $mail->active && $mail->sufficient) {
0337d704 438 return true;
439 }
440 }
441 return false;
442 }
443
441c2451 444 // public function delete_email() {{{2
0337d704 445
612a2d8a 446 public function delete_email($email)
0337d704 447 {
0337d704 448 if (!$this->other_active($email)) {
449 return ERROR_INACTIVE_REDIRECTION;
450 }
08cce2ff 451 XDB::execute('DELETE FROM emails WHERE uid={?} AND email={?}', $this->uid, $email);
732e5855 452 S::logger()->log('email_del',$email.($this->uid!=S::v('uid') ? " (admin on {$this->uid})" : ""));
11ed26e5
VZ
453 foreach ($this->emails as $i => $mail) {
454 if ($email == $mail->email) {
0337d704 455 unset($this->emails[$i]);
456 }
3c1e6a1e 457 }
ccdbc270 458 check_redirect($this);
0337d704 459 return SUCCESS;
460 }
461
441c2451 462 // public function add_email() {{{2
612a2d8a 463
464 public function add_email($email)
0337d704 465 {
0337d704 466 $email_stripped = strtolower(trim($email));
467 if (!isvalid_email($email_stripped)) {
468 return ERROR_INVALID_EMAIL;
469 }
470 if (!isvalid_email_redirection($email_stripped)) {
471 return ERROR_LOOP_EMAIL;
472 }
08cce2ff 473 XDB::execute('REPLACE INTO emails (uid,email,flags) VALUES({?},{?},"active")', $this->uid, $email);
3c1e6a1e 474 if ($logger = S::v('log', null)) { // may be absent --> step4.php
732e5855 475 S::logger()->log('email_add',$email.($this->uid!=S::v('uid') ? " (admin on {$this->uid})" : ""));
0337d704 476 }
3c1e6a1e 477 foreach ($this->emails as $mail) {
478 if ($mail->email == $email_stripped) {
0337d704 479 return SUCCESS;
480 }
3c1e6a1e 481 }
c66de9a0 482 $this->emails[] = new EmailRedirection($this->uid, array($email, 'active', '', 0, null, '0000-00-00', '0000-00-00', 0));
ca6d07f4 483
484 // security stuff
a7de4ef7 485 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->uid);
ccdbc270 486 check_redirect($this);
0337d704 487 return SUCCESS;
488 }
489
441c2451 490 // public function modify_email() {{{2
0337d704 491
612a2d8a 492 public function modify_email($emails_actifs, $emails_rewrite)
0337d704 493 {
441c2451 494 foreach ($this->emails as &$mail) {
495 if (in_array($mail->email, $emails_actifs)) {
11ed26e5 496 $mail->activate();
3c1e6a1e 497 } else {
11ed26e5 498 $mail->deactivate();
3c1e6a1e 499 }
11ed26e5 500 $mail->set_rewrite($emails_rewrite[$mail->email]);
0337d704 501 }
ccdbc270 502 check_redirect($this);
0337d704 503 }
504
441c2451 505 // public function modify_one_email() {{{2
506
eaf30d86 507 public function modify_one_email($email, $activate)
ccdbc270 508 {
b7582015 509 $allinactive = true;
510 $thisone = false;
8ffa657a 511 foreach ($this->emails as $i=>$mail) {
512 if ($mail->email == $email) {
b7582015 513 $thisone = $i;
8ffa657a 514 }
11ed26e5 515 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
8ffa657a 516 }
b7582015 517 if ($thisone === false) {
518 return ERROR_INVALID_EMAIL;
519 }
ccdbc270 520 if ($allinactive || $activate) {
11ed26e5 521 $this->emails[$thisone]->activate();
ccdbc270 522 } else {
11ed26e5 523 $this->emails[$thisone]->deactivate();
ccdbc270 524 }
525 check_redirect($this);
b7582015 526 if ($allinactive && !$activate) {
527 return ERROR_INACTIVE_REDIRECTION;
528 } else {
529 return SUCCESS;
eaf30d86 530 }
8ffa657a 531 }
532
441c2451 533 // public function modify_one_email_redirect() {{{2
534
612a2d8a 535 public function modify_one_email_redirect($email, $redirect)
536 {
441c2451 537 foreach ($this->emails as &$mail) {
612a2d8a 538 if ($mail->email == $email) {
11ed26e5 539 $mail->set_rewrite($redirect);
ccdbc270 540 check_redirect($this);
541 return;
612a2d8a 542 }
543 }
544 }
441c2451 545
11ed26e5 546 // function clean_errors() {{{2
441c2451 547
11ed26e5 548 public function clean_errors($email)
441c2451 549 {
550 foreach ($this->emails as &$mail) {
551 if ($mail->email == $email) {
e1547442 552 check_redirect($this);
11ed26e5 553 return $mail->clean_errors();
441c2451 554 }
555 }
556 return false;
557 }
558
559 // function disable() {{{2
560
561 public function disable()
562 {
563 XDB::execute("UPDATE emails
564 SET flags = 'disable'
565 WHERE flags = 'active' AND uid = {?}", $this->uid);
566 foreach ($this->emails as &$mail) {
11ed26e5 567 if ($mail->active && $mail->has_disable()) {
441c2451 568 $mail->disabled = true;
569 $mail->active = false;
570 }
571 }
e1547442 572 check_redirect($this);
441c2451 573 }
574
575 // function enable() {{{2
576
577 public function enable()
578 {
579 XDB::execute("UPDATE emails
580 SET flags = 'active'
581 WHERE flags = 'disable' AND uid = {?}", $this->uid);
582 foreach ($this->emails as &$mail) {
583 if ($mail->disabled) {
584 $mail->active = true;
585 $mail->disabled = false;
586 }
e1547442 587 check_redirect($this);
441c2451 588 }
589 }
590
591 // function get_broken_mx() {{{2
ccdbc270 592
612a2d8a 593 public function get_broken_mx()
ccdbc270 594 {
3083bd93 595 $res = XDB::query("SELECT host, text
8af1d78f
FB
596 FROM mx_watch
597 WHERE state != 'ok'");
120bd636 598 if (!$res->numRows()) {
ccdbc270 599 return array();
600 }
c754cf5b 601 $mxs = $res->fetchAllAssoc();
ccdbc270 602 $mails = array();
603 foreach ($this->emails as &$mail) {
11ed26e5 604 if ($mail->active && strstr($mail->email, '@') !== false) {
ccdbc270 605 list(,$domain) = explode('@', $mail->email);
606 getmxrr($domain, $lcl_mxs);
607 if (empty($lcl_mxs)) {
608 $lcl_mxs = array($domain);
609 }
610 $broken = false;
611 foreach ($mxs as &$mx) {
612 foreach ($lcl_mxs as $lcl) {
c754cf5b 613 if (fnmatch($mx['host'], $lcl)) {
ccdbc270 614 $broken = $mx['text'];
615 break;
616 }
617 }
618 if ($broken) {
3083bd93 619 $mails[] = array('mail' => $mail->email, 'text' => $broken);
f653ff3d 620 break;
ccdbc270 621 }
622 }
623 }
624 }
625 return $mails;
626 }
e97e9b8f
VZ
627
628 // function active_emails() {{{2
629
630 public function active_emails()
631 {
632 $emails = array();
633 foreach ($this->emails as $mail) {
634 if ($mail->active) {
635 $emails[] = $mail;
636 }
637 }
638 return $emails;
639 }
45282934
VZ
640
641 // function get_uid() {{{2
642
643 public function get_uid()
644 {
645 return $this->uid;
646 }
0337d704 647}
648
a7de4ef7 649// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 650?>