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