Switches email related classes to the new User model.
[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.
12a587df 30function fix_bestalias(User &$user)
0337d704 31{
11ed26e5
VZ
32 $res = XDB::query("SELECT COUNT(*)
33 FROM aliases
34 WHERE id = {?} AND FIND_IN_SET('bestalias', flags) AND type != 'homonyme'",
12a587df 35 $user->id());
11ed26e5 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)
12a587df 44 LIMIT 1", $user->id());
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
12a587df 83 private $user;
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
12a587df 89 public function __construct(User &$user)
0337d704 90 {
12a587df 91 if (!$user) {
3c1e6a1e 92 return;
93 }
11ed26e5 94
12a587df
VZ
95 $this->user = &$user;
96 $res = XDB::query('SELECT email FROM emails WHERE uid = {?} AND flags = "filter"', $user->id());
3c1e6a1e 97 if ($res->numRows()) {
612a2d8a 98 $this->state = $res->fetchOneCell();
3c1e6a1e 99 } else {
100 $this->state = 'tag_and_drop_spams';
12a587df
VZ
101 $res = XDB::query(
102 "INSERT INTO emails (uid, email, rewrite, panne, flags)
103 VALUES ({?}, 'tag_and_drop_spams', '', '0000-00-00', 'filter')",
104 $user->id());
3c1e6a1e 105 }
0337d704 106 }
107
441c2451 108 // public function change() {{{2
0337d704 109
11ed26e5 110 public function change($state)
0337d704 111 {
612a2d8a 112 $this->state = is_int($state) ? $this->_states[$state] : $state;
12a587df
VZ
113 XDB::execute('UPDATE emails SET email = {?} WHERE uid = {?} AND flags = "filter"',
114 $this->state, $this->user->id());
0337d704 115 }
116
441c2451 117 // pubic function level() {{{2
0337d704 118
612a2d8a 119 public function level()
120 {
121 return array_search($this->state, $this->_states);
122 }
0337d704 123}
124
441c2451 125// class Email {{{1
11ed26e5
VZ
126// Represents an "email address" used as final recipient for plat/al-managed
127// addresses; it can be subclasses a Redirection emails (third-party) or as
128// Storage emails (Polytechnique.org).
129abstract class Email
0337d704 130{
12a587df 131 protected $user;
612a2d8a 132
11ed26e5
VZ
133 // Basic email properties; $sufficient indicates if the email can be used as
134 // an unique redirection; $email contains the delivery email address.
135 public $type;
136 public $sufficient;
612a2d8a 137 public $email;
11ed26e5
VZ
138 public $display_email;
139
140 // Redirection status properties.
612a2d8a 141 public $active;
142 public $broken;
441c2451 143 public $disabled;
612a2d8a 144 public $rewrite;
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
12a587df 179 public function __construct(User &$user, $row)
0337d704 180 {
12a587df 181 $this->user = &$user;
11ed26e5
VZ
182 $this->sufficient = true;
183
2069538b 184 list($this->email, $flags, $this->rewrite, $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'
12a587df
VZ
199 WHERE uid = {?} AND email = {?}", $this->user->id(), $this->email);
200 S::logger()->log("email_on", $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : ""));
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 =''
12a587df
VZ
212 WHERE uid = {?} AND email = {?}", $this->user->id(), $this->email);
213 S::logger()->log("email_off", $this->email . ($this->user->id() != S::v('uid') ? "(admin on {$this->user->login()})" : "") );
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 }
12a587df 228 XDB::execute('UPDATE emails SET rewrite = {?} WHERE uid = {?} AND email = {?}', $rewrite, $this->user->id(), $this->email);
11ed26e5 229 $this->rewrite = $rewrite;
3c1e6a1e 230 return;
0337d704 231 }
232
11ed26e5 233 // public function clean_errors() {{{2
441c2451 234
11ed26e5 235 public function clean_errors()
441c2451 236 {
237 if (!S::has_perms()) {
238 return false;
239 }
240 $this->panne = 0;
241 $this->panne_level = 0;
242 $this->last = 0;
243 return XDB::execute("UPDATE emails
244 SET panne_level = 0, panne = 0, last = 0
245 WHERE uid = {?} AND email = {?}",
12a587df 246 $this->user->id(), $this->email);
11ed26e5
VZ
247 }
248
249 // public function has_rewrite() {{{2
250
251 public function has_rewrite()
252 {
253 return true;
254 }
255
256 // public function is_removable() {{{2
257
258 public function is_removable()
259 {
260 return true;
261 }
262
263 // public function has_disable() {{{2
264
265 public function has_disable()
266 {
267 return true;
441c2451 268 }
0337d704 269}
270
afde0a3a
VZ
271// class EmailStorage {{{1
272// Implementation of Email for email storage backends from Polytechnique.org.
273class EmailStorage extends Email
274{
275 // Shortname to realname mapping for known mail storage backends.
276 private $display_names = array(
277 'imap' => 'Accès de secours aux emails (IMAP)',
690c8519 278 'googleapps' => 'Compte Google Apps',
afde0a3a
VZ
279 );
280
281 // Retrieves the current list of actives storages.
282 private function get_storages()
283 {
284 $res = XDB::query("SELECT mail_storage
285 FROM auth_user_md5
12a587df 286 WHERE user_id = {?}", $this->user->id());
113f6de8 287 return new PlFlagSet($res->fetchOneCell());
afde0a3a
VZ
288 }
289
290 // Updates the list of active storages.
291 private function set_storages($storages)
292 {
293 XDB::execute("UPDATE auth_user_md5
294 SET mail_storage = {?}
12a587df 295 WHERE user_id = {?}", $storages, $this->user->id());
afde0a3a
VZ
296 }
297
298 // Returns the list of allowed storages for the @p user.
12a587df 299 static public function get_allowed_storages(User &$user)
afde0a3a
VZ
300 {
301 global $globals;
302 $storages = array();
303
304 // Google Apps storage is available for users with valid Google Apps account.
305 require_once 'googleapps.inc.php';
306 if ($globals->mailstorage->googleapps_domain &&
12a587df 307 GoogleAppsAccount::account_status($user->id()) == 'active') {
afde0a3a
VZ
308 $storages[] = 'googleapps';
309 }
310
311 // IMAP storage is always visible to administrators, and is allowed for
312 // everyone when the service is marked as 'active'.
313 if ($globals->mailstorage->imap_active || S::has_perms()) {
314 $storages[] = 'imap';
315 }
316
317 return $storages;
318 }
319
320
12a587df 321 public function __construct(User &$user, $name)
afde0a3a 322 {
12a587df 323 $this->user = &$user;
afde0a3a
VZ
324 $this->email = $name;
325 $this->display_email = (isset($this->display_names[$name]) ? $this->display_names[$name] : $name);
326
327 $storages = $this->get_storages();
328 $this->sufficient = ($name == 'googleapps');
329 $this->active = $storages->hasFlag($name);
330 $this->broken = false;
331 $this->disabled = false;
332 $this->rewrite = '';
333 $this->panne = $this->last = $this->panne_level = 0;
334 }
335
336 public function activate()
337 {
338 if (!$this->active) {
339 $storages = $this->get_storages();
340 $storages->addFlag($this->email);
341 $this->set_storages($storages);
342 $this->active = true;
343 }
344 }
345
346 public function deactivate()
347 {
348 if ($this->active) {
349 $storages = $this->get_storages();
350 $storages->rmFlag($this->email);
351 $this->set_storages($storages);
352 $this->active = false;
353 }
354
355 }
356
357 // Source rewrite can't be enabled for email storage addresses.
358 public function set_rewrite($rewrite) {}
359
360 // Email storage are not supposed to be broken, hence not supposed to be
361 // cleaned-up.
362 public function clean_errors() {}
363
364 // Capabilities.
365 public function has_rewrite() { return false; }
366 public function is_removable() { return false; }
367 public function has_disable() { return false; }
368}
369
441c2451 370// class Redirect {{{1
11ed26e5
VZ
371// Redirect is a placeholder class for an user's active redirections (third-party
372// redirection email, or Polytechnique.org mail storages).
0337d704 373class Redirect
374{
441c2451 375 // properties {{{2
612a2d8a 376
377 private $flag_active = 'active';
12a587df 378 private $user;
612a2d8a 379
380 public $emails;
381 public $bogo;
0337d704 382
441c2451 383 // constructor {{{2
0337d704 384
12a587df 385 public function __construct(User &$user)
0337d704 386 {
12a587df
VZ
387 $this->user = &$user;
388 $this->bogo = new Bogo($user);
11ed26e5 389
afde0a3a 390 // Adds third-party email redirections.
612a2d8a 391 $res = XDB::iterRow("SELECT email, flags, rewrite, panne, last, panne_level
392 FROM emails
12a587df 393 WHERE uid = {?} AND flags != 'filter'", $user->id());
11ed26e5 394 $this->emails = Array();
0337d704 395 while ($row = $res->next()) {
12a587df 396 $this->emails[] = new EmailRedirection($user, $row);
0337d704 397 }
afde0a3a
VZ
398
399 // Adds local email storage backends.
12a587df
VZ
400 foreach (EmailStorage::get_allowed_storages($user) as $storage) {
401 $this->emails[] = new EmailStorage($user, $storage);
afde0a3a 402 }
0337d704 403 }
404
441c2451 405 // public function other_active() {{{2
0337d704 406
612a2d8a 407 public function other_active($email)
0337d704 408 {
409 foreach ($this->emails as $mail) {
11ed26e5 410 if ($mail->email != $email && $mail->active && $mail->sufficient) {
0337d704 411 return true;
412 }
413 }
414 return false;
415 }
416
441c2451 417 // public function delete_email() {{{2
0337d704 418
612a2d8a 419 public function delete_email($email)
0337d704 420 {
0337d704 421 if (!$this->other_active($email)) {
422 return ERROR_INACTIVE_REDIRECTION;
423 }
12a587df
VZ
424 XDB::execute('DELETE FROM emails WHERE uid = {?} AND email = {?}', $this->user->id(), $email);
425 S::logger()->log('email_del', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
11ed26e5
VZ
426 foreach ($this->emails as $i => $mail) {
427 if ($email == $mail->email) {
0337d704 428 unset($this->emails[$i]);
429 }
3c1e6a1e 430 }
ccdbc270 431 check_redirect($this);
0337d704 432 return SUCCESS;
433 }
434
441c2451 435 // public function add_email() {{{2
612a2d8a 436
437 public function add_email($email)
0337d704 438 {
0337d704 439 $email_stripped = strtolower(trim($email));
440 if (!isvalid_email($email_stripped)) {
441 return ERROR_INVALID_EMAIL;
442 }
443 if (!isvalid_email_redirection($email_stripped)) {
444 return ERROR_LOOP_EMAIL;
445 }
12a587df 446 XDB::execute('REPLACE INTO emails (uid,email,flags) VALUES({?},{?},"active")', $this->user->id(), $email);
3c1e6a1e 447 if ($logger = S::v('log', null)) { // may be absent --> step4.php
12a587df 448 S::logger()->log('email_add', $email . ($this->user->id() != S::v('uid') ? " (admin on {$this->user->login()})" : ""));
0337d704 449 }
3c1e6a1e 450 foreach ($this->emails as $mail) {
451 if ($mail->email == $email_stripped) {
0337d704 452 return SUCCESS;
453 }
3c1e6a1e 454 }
12a587df 455 $this->emails[] = new EmailRedirection($this->user, array($email, 'active', '', '0000-00-00', '0000-00-00', 0));
ca6d07f4 456
457 // security stuff
12a587df 458 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user->login());
ccdbc270 459 check_redirect($this);
0337d704 460 return SUCCESS;
461 }
462
441c2451 463 // public function modify_email() {{{2
0337d704 464
612a2d8a 465 public function modify_email($emails_actifs, $emails_rewrite)
0337d704 466 {
441c2451 467 foreach ($this->emails as &$mail) {
468 if (in_array($mail->email, $emails_actifs)) {
11ed26e5 469 $mail->activate();
3c1e6a1e 470 } else {
11ed26e5 471 $mail->deactivate();
3c1e6a1e 472 }
11ed26e5 473 $mail->set_rewrite($emails_rewrite[$mail->email]);
0337d704 474 }
ccdbc270 475 check_redirect($this);
0337d704 476 }
477
441c2451 478 // public function modify_one_email() {{{2
479
eaf30d86 480 public function modify_one_email($email, $activate)
ccdbc270 481 {
b7582015 482 $allinactive = true;
483 $thisone = false;
8ffa657a 484 foreach ($this->emails as $i=>$mail) {
485 if ($mail->email == $email) {
b7582015 486 $thisone = $i;
8ffa657a 487 }
11ed26e5 488 $allinactive &= !$mail->active || !$mail->sufficient || $mail->email == $email;
8ffa657a 489 }
b7582015 490 if ($thisone === false) {
491 return ERROR_INVALID_EMAIL;
492 }
ccdbc270 493 if ($allinactive || $activate) {
11ed26e5 494 $this->emails[$thisone]->activate();
ccdbc270 495 } else {
11ed26e5 496 $this->emails[$thisone]->deactivate();
ccdbc270 497 }
498 check_redirect($this);
b7582015 499 if ($allinactive && !$activate) {
500 return ERROR_INACTIVE_REDIRECTION;
501 } else {
502 return SUCCESS;
eaf30d86 503 }
8ffa657a 504 }
505
441c2451 506 // public function modify_one_email_redirect() {{{2
507
612a2d8a 508 public function modify_one_email_redirect($email, $redirect)
509 {
441c2451 510 foreach ($this->emails as &$mail) {
612a2d8a 511 if ($mail->email == $email) {
11ed26e5 512 $mail->set_rewrite($redirect);
ccdbc270 513 check_redirect($this);
514 return;
612a2d8a 515 }
516 }
517 }
441c2451 518
11ed26e5 519 // function clean_errors() {{{2
441c2451 520
11ed26e5 521 public function clean_errors($email)
441c2451 522 {
523 foreach ($this->emails as &$mail) {
524 if ($mail->email == $email) {
e1547442 525 check_redirect($this);
11ed26e5 526 return $mail->clean_errors();
441c2451 527 }
528 }
529 return false;
530 }
531
532 // function disable() {{{2
533
534 public function disable()
535 {
536 XDB::execute("UPDATE emails
537 SET flags = 'disable'
12a587df 538 WHERE flags = 'active' AND uid = {?}", $this->user->id);
441c2451 539 foreach ($this->emails as &$mail) {
11ed26e5 540 if ($mail->active && $mail->has_disable()) {
441c2451 541 $mail->disabled = true;
542 $mail->active = false;
543 }
544 }
e1547442 545 check_redirect($this);
441c2451 546 }
547
548 // function enable() {{{2
549
550 public function enable()
551 {
552 XDB::execute("UPDATE emails
553 SET flags = 'active'
12a587df 554 WHERE flags = 'disable' AND uid = {?}", $this->user->id);
441c2451 555 foreach ($this->emails as &$mail) {
556 if ($mail->disabled) {
557 $mail->active = true;
558 $mail->disabled = false;
559 }
e1547442 560 check_redirect($this);
441c2451 561 }
562 }
563
564 // function get_broken_mx() {{{2
ccdbc270 565
612a2d8a 566 public function get_broken_mx()
ccdbc270 567 {
3083bd93 568 $res = XDB::query("SELECT host, text
8af1d78f
FB
569 FROM mx_watch
570 WHERE state != 'ok'");
120bd636 571 if (!$res->numRows()) {
ccdbc270 572 return array();
573 }
c754cf5b 574 $mxs = $res->fetchAllAssoc();
ccdbc270 575 $mails = array();
576 foreach ($this->emails as &$mail) {
11ed26e5 577 if ($mail->active && strstr($mail->email, '@') !== false) {
ccdbc270 578 list(,$domain) = explode('@', $mail->email);
579 getmxrr($domain, $lcl_mxs);
580 if (empty($lcl_mxs)) {
581 $lcl_mxs = array($domain);
582 }
583 $broken = false;
584 foreach ($mxs as &$mx) {
585 foreach ($lcl_mxs as $lcl) {
c754cf5b 586 if (fnmatch($mx['host'], $lcl)) {
ccdbc270 587 $broken = $mx['text'];
588 break;
589 }
590 }
591 if ($broken) {
3083bd93 592 $mails[] = array('mail' => $mail->email, 'text' => $broken);
f653ff3d 593 break;
ccdbc270 594 }
595 }
596 }
597 }
598 return $mails;
599 }
e97e9b8f
VZ
600
601 // function active_emails() {{{2
602
603 public function active_emails()
604 {
605 $emails = array();
606 foreach ($this->emails as $mail) {
607 if ($mail->active) {
608 $emails[] = $mail;
609 }
610 }
611 return $emails;
612 }
45282934
VZ
613
614 // function get_uid() {{{2
615
616 public function get_uid()
617 {
12a587df 618 return $this->user->id();
45282934 619 }
0337d704 620}
621
a7de4ef7 622// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 623?>