2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
23 define("ERROR_INACTIVE_REDIRECTION", 2);
24 define("ERROR_INVALID_EMAIL", 3);
25 define("ERROR_LOOP_EMAIL", 4);
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)
32 $res = XDB
::query("SELECT COUNT(*)
34 WHERE uid = {?} AND FIND_IN_SET('bestalias', flags) AND type != 'homonyme'",
36 if ($res->fetchOneCell()) {
40 XDB
::execute("UPDATE aliases
41 SET flags=CONCAT(flags,',','bestalias')
42 WHERE uid={?} AND type!='homonyme'
43 ORDER BY !FIND_IN_SET('usage',flags),alias LIKE '%.%', LENGTH(alias)
44 LIMIT 1", $user->id());
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)
55 $em = trim(rtrim($str));
56 $em = str_replace('<', '', $em);
57 $em = str_replace('>', '', $em);
58 if (strpos($em, '@') === false
) {
61 list($ident, $dom) = explode('@', $em);
62 if ($dom == $globals->mail
->domain ||
$dom == $globals->mail
->domain2
) {
63 list($ident1) = explode('_', $ident);
64 list($ident) = explode('+', $ident1);
66 return $ident . '@' . $dom;
69 // function isvalid_email_redirection() {{{1
70 /** vérifie si une adresse email convient comme adresse de redirection
71 * @param $email l'adresse email a verifier
74 function isvalid_email_redirection($email)
76 return isvalid_email($email) &&
77 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
80 // function ids_from_mails() {{{1
81 // Converts an array of emails to an array of email => uid
82 function ids_from_mails(array $emails)
85 $domain_mails = array();
86 $alias_mails = array();
87 $other_mails = array();
89 // Determine the type of the email adresses. It can eiher be a domain
90 // email (@polytechnique.org), an alias email (@melix.net) or any other
91 // email (potentially used as a redirection by one user)
92 foreach ($emails as $email) {
93 if (strpos($email, '@') === false
) {
95 $domain = $globals->mail
->domain2
;
97 list($user, $domain) = explode('@', $email);
99 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
) {
100 list($user) = explode('+', $user);
101 list($user) = explode('_', $user);
102 $alias_mails[$email] = $user . "@" . $globals->mail
->alias_dom
;
103 } elseif ($domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
104 list($user) = explode('+', $user);
105 list($user) = explode('_', $user);
106 $domain_mails[$email] = $user;
108 $other_mails[] = $email;
113 // Look up user ids for addresses in domain
114 $alias_uids = array();
115 if (count($domain_mails)) {
116 $res = XDB
::query("SELECT alias, uid
118 WHERE alias IN {?}", array_unique($domain_mails));
119 foreach ($res->fetchAllRow() as $row) {
120 list ($alias, $id) = $row;
121 $domain_uids[$alias] = $id;
124 // Connect emails with uids
125 foreach ($domain_mails as $email => $user) {
126 // Some 'domain' emails might be invalid.
127 if (array_key_exists($user, $domain_uids)) {
128 $uids[$email] = $domain_uids[$user];
132 // Look up user ids for addresses in our alias domain
133 $alias_uids = array();
134 if (count($alias_mails)) {
135 $res = XDB
::query("SELECT v.alias, a.uid
137 INNER JOIN virtual_redirect AS r USING(vid)
138 INNER JOIN aliases AS a ON (a.type = 'a_vie'
139 AND r.redirect = CONCAT(a.alias, '@{$globals->mail->domain2}'))
140 WHERE v.alias IN {?}", array_unique($alias_mails));
141 foreach ($res->fetchAllRow() as $row) {
142 list ($alias, $id) = $row;
143 $alias_uids[$alias] = $id;
146 // Connect emails with uids
147 foreach ($alias_mails as $email => $user) {
148 if (array_key_exists($user, $alias_uids)) {
149 $uids[$email] = $alias_uids[$user];
153 // Look up user ids for other addresses in the email redirection list
154 if (count($other_mails)) {
155 $lowerupper = array();
156 foreach ($other_mails as $mail) {
157 $lowerupper[strtolower($mail)] = $mail;
159 $res = XDB
::query("SELECT email, uid
161 WHERE email IN {?}", $other_mails);
162 foreach ($res->fetchAllRow() as $row) {
163 list ($email, $uid) = $row;
164 $uids[$lowerupper[strtolower($email)]] = $uid;
172 // The Bogo class represents a spam filtering level in plat/al architecture.
179 private $_states = Array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
183 public function __construct(User
&$user)
189 $this->user
= &$user;
190 $res = XDB
::query('SELECT email FROM emails WHERE uid = {?} AND flags = "filter"', $user->id());
191 if ($res->numRows()) {
192 $this->state
= $res->fetchOneCell();
194 $this->state
= 'tag_and_drop_spams';
196 "INSERT INTO emails (uid, email, rewrite, panne, flags)
197 VALUES ({?}, 'tag_and_drop_spams', '', '0000-00-00', 'filter')",
202 // public function change() {{{2
204 public function change($state)
206 $this->state
= is_int($state) ?
$this->_states
[$state] : $state;
207 XDB
::execute('UPDATE emails SET email = {?} WHERE uid = {?} AND flags = "filter"',
208 $this->state
, $this->user
->id());
211 // pubic function level() {{{2
213 public function level()
215 return array_search($this->state
, $this->_states
);
220 // Represents an "email address" used as final recipient for plat/al-managed
221 // addresses; it can be subclasses a Redirection emails (third-party) or as
222 // Storage emails (Polytechnique.org).
227 // Basic email properties; $sufficient indicates if the email can be used as
228 // an unique redirection; $email contains the delivery email address.
232 public $display_email;
234 // Redirection status properties.
239 public $allow_rewrite;
242 // Redirection bounces stats.
247 // Activates the email address as a redirection.
248 public abstract function activate();
250 // Deactivates the email address as a redirection.
251 public abstract function deactivate();
253 // Sets the rewrite rule for the given address.
254 public abstract function set_rewrite($rewrite);
256 // Resets the error counts associated with the redirection.
257 public abstract function clean_errors();
259 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
260 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
261 // can be definitively removed; 'disable' indicates if the email has a third
262 // status 'disabled' in addition to 'active' and 'inactive').
263 public abstract function has_rewrite();
264 public abstract function is_removable();
265 public abstract function has_disable();
268 // class EmailRedirection {{{1
269 // Implementation of Email for third-party redirection (redirection of emails to
270 // external user-supplied addresses).
271 class EmailRedirection
extends Email
275 public function __construct(User
&$user, $row)
277 $this->user
= &$user;
278 $this->sufficient
= true
;
280 list($this->email
, $flags, $this->rewrite
, $this->allow_rewrite
, $this->hash
, $this->panne
, $this->last
, $this->panne_level
) = $row;
281 $this->display_email
= $this->email
;
282 $this->active
= ($flags == 'active');
283 $this->broken
= ($flags == 'panne');
284 $this->disabled
= ($flags == 'disable');
287 // public function activate() {{{2
289 public function activate()
291 if (!$this->active
) {
292 XDB
::execute("UPDATE emails
293 SET panne_level = IF(flags = 'panne', panne_level - 1, panne_level),
295 WHERE uid = {?} AND email = {?}", $this->user
->id(), $this->email
);
296 S
::logger()->log("email_on", $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : ""));
297 $this->active
= true
;
298 $this->broken
= false
;
302 // public function deactivate() {{{2
304 public function deactivate()
307 XDB
::execute("UPDATE emails SET flags =''
308 WHERE uid = {?} AND email = {?}", $this->user
->id(), $this->email
);
309 S
::logger()->log("email_off", $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : "") );
310 $this->active
= false
;
314 // public function set_rewrite() {{{2
316 public function set_rewrite($rewrite)
318 if ($this->rewrite
== $rewrite) {
321 if (!$rewrite ||
!isvalid_email($rewrite)) {
324 XDB
::execute('UPDATE emails SET rewrite = {?} WHERE uid = {?} AND email = {?}', $rewrite, $this->user
->id(), $this->email
);
325 $this->rewrite
= $rewrite;
326 if (!$this->allow_rewrite
) {
328 if (empty($this->hash
)) {
329 $this->hash
= rand_url_id();
330 XDB
::execute("UPDATE emails
332 WHERE uid = {?} AND email = {?}", $this->hash
, $this->user
->id(), $this->email
);
334 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
335 $mail->assign('mail', $this);
336 $mail->assign('user', $this->user
);
337 $mail->assign('baseurl', $globals->baseurl
);
338 $mail->assign('sitename', $globals->core
->sitename
);
339 $mail->assign('to', $this->email
);
340 $mail->send($this->user
->isEmailFormatHtml());
345 // public function clean_errors() {{{2
347 public function clean_errors()
353 $this->panne_level
= 0;
355 return XDB
::execute("UPDATE emails
356 SET panne_level = 0, panne = 0, last = 0
357 WHERE uid = {?} AND email = {?}",
358 $this->user
->id(), $this->email
);
361 // public function has_rewrite() {{{2
363 public function has_rewrite()
368 // public function is_removable() {{{2
370 public function is_removable()
375 // public function has_disable() {{{2
377 public function has_disable()
383 // class EmailStorage {{{1
384 // Implementation of Email for email storage backends from Polytechnique.org.
385 class EmailStorage
extends Email
387 // Shortname to realname mapping for known mail storage backends.
388 private $display_names = array(
389 'imap' => 'Accès de secours aux emails (IMAP)',
390 'googleapps' => 'Compte Google Apps',
393 // Retrieves the current list of actives storages.
394 private function get_storages()
396 return new PlFlagSet(XDB
::fetchOneCell('SELECT storage
402 // Updates the list of active storages.
403 private function set_storages($storages)
405 XDB
::execute("UPDATE email_options
407 WHERE uid = {?}", $storages, $this->user
->id());
410 // Returns the list of allowed storages for the @p user.
411 static public function get_allowed_storages(User
&$user)
416 // Google Apps storage is available for users with valid Google Apps account.
417 require_once 'googleapps.inc.php';
418 if ($globals->mailstorage
->googleapps_domain
&&
419 GoogleAppsAccount
::account_status($user->id()) == 'active') {
420 $storages[] = 'googleapps';
423 // IMAP storage is always visible to administrators, and is allowed for
424 // everyone when the service is marked as 'active'.
425 if ($globals->mailstorage
->imap_active || S
::admin()) {
426 $storages[] = 'imap';
433 public function __construct(User
&$user, $name)
435 $this->user
= &$user;
436 $this->email
= $name;
437 $this->display_email
= (isset($this->display_names
[$name]) ?
$this->display_names
[$name] : $name);
439 $storages = $this->get_storages();
440 $this->sufficient
= ($name == 'googleapps');
441 $this->active
= $storages->hasFlag($name);
442 $this->broken
= false
;
443 $this->disabled
= false
;
445 $this->panne
= $this->last
= $this->panne_level
= 0;
448 public function activate()
450 if (!$this->active
) {
451 $storages = $this->get_storages();
452 $storages->addFlag($this->email
);
453 $this->set_storages($storages);
454 $this->active
= true
;
458 public function deactivate()
461 $storages = $this->get_storages();
462 $storages->rmFlag($this->email
);
463 $this->set_storages($storages);
464 $this->active
= false
;
469 // Source rewrite can't be enabled for email storage addresses.
470 public function set_rewrite($rewrite) {}
472 // Email storage are not supposed to be broken, hence not supposed to be
474 public function clean_errors() {}
477 public function has_rewrite() { return false
; }
478 public function is_removable() { return false
; }
479 public function has_disable() { return false
; }
482 // class Redirect {{{1
483 // Redirect is a placeholder class for an user's active redirections (third-party
484 // redirection email, or Polytechnique.org mail storages).
489 private $flag_active = 'active';
497 public function __construct(User
&$user)
499 $this->user
= &$user;
500 $this->bogo
= new Bogo($user);
502 // Adds third-party email redirections.
503 $res = XDB
::iterRow("SELECT email, flags, rewrite, allow_rewrite, hash, panne, last, panne_level
505 WHERE uid = {?} AND flags != 'filter'", $user->id());
506 $this->emails
= Array();
507 while ($row = $res->next()) {
508 $this->emails
[] = new EmailRedirection($user, $row);
511 // Adds local email storage backends.
512 foreach (EmailStorage
::get_allowed_storages($user) as $storage) {
513 $this->emails
[] = new EmailStorage($user, $storage);
517 // public function other_active() {{{2
519 public function other_active($email)
521 foreach ($this->emails
as $mail) {
522 if ($mail->email
!= $email && $mail->active
&& $mail->sufficient
) {
529 // public function delete_email() {{{2
531 public function delete_email($email)
533 if (!$this->other_active($email)) {
534 return ERROR_INACTIVE_REDIRECTION
;
536 XDB
::execute('DELETE FROM emails WHERE uid = {?} AND email = {?}', $this->user
->id(), $email);
537 S
::logger()->log('email_del', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
538 foreach ($this->emails
as $i => $mail) {
539 if ($email == $mail->email
) {
540 unset($this->emails
[$i]);
543 check_redirect($this);
547 // public function add_email() {{{2
549 public function add_email($email)
551 $email_stripped = strtolower(trim($email));
552 if (!isvalid_email($email_stripped)) {
553 return ERROR_INVALID_EMAIL
;
555 if (!isvalid_email_redirection($email_stripped)) {
556 return ERROR_LOOP_EMAIL
;
558 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
559 XDB
::execute('REPLACE INTO emails (uid, email, flags)
560 VALUES ({?}, {?}, \'active\')',
561 $this->user
->id(), $email);
562 if ($logger = S
::v('log', null
)) { // may be absent --> step4.php
563 S
::logger()->log('email_add', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
565 foreach ($this->emails
as $mail) {
566 if ($mail->email
== $email_stripped) {
570 $this->emails
[] = new EmailRedirection($this->user
, array($email, 'active', '', 0, null
, '0000-00-00', '0000-00-00', 0));
573 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user
->login());
574 check_redirect($this);
578 // public function modify_email() {{{2
580 public function modify_email($emails_actifs, $emails_rewrite)
582 foreach ($this->emails
as &$mail) {
583 if (in_array($mail->email
, $emails_actifs)) {
588 $mail->set_rewrite($emails_rewrite[$mail->email
]);
590 check_redirect($this);
593 // public function modify_one_email() {{{2
595 public function modify_one_email($email, $activate)
599 foreach ($this->emails
as $i=>$mail) {
600 if ($mail->email
== $email) {
603 $allinactive &= !$mail->active ||
!$mail->sufficient ||
$mail->email
== $email;
605 if ($thisone === false
) {
606 return ERROR_INVALID_EMAIL
;
608 if ($allinactive ||
$activate) {
609 $this->emails
[$thisone]->activate();
611 $this->emails
[$thisone]->deactivate();
613 check_redirect($this);
614 if ($allinactive && !$activate) {
615 return ERROR_INACTIVE_REDIRECTION
;
621 // public function modify_one_email_redirect() {{{2
623 public function modify_one_email_redirect($email, $redirect)
625 foreach ($this->emails
as &$mail) {
626 if ($mail->email
== $email) {
627 $mail->set_rewrite($redirect);
628 check_redirect($this);
634 // function clean_errors() {{{2
636 public function clean_errors($email)
638 foreach ($this->emails
as &$mail) {
639 if ($mail->email
== $email) {
640 check_redirect($this);
641 return $mail->clean_errors();
647 // function disable() {{{2
649 public function disable()
651 XDB
::execute("UPDATE emails
652 SET flags = 'disable'
653 WHERE flags = 'active' AND uid = {?}", $this->user
->id());
654 foreach ($this->emails
as &$mail) {
655 if ($mail->active
&& $mail->has_disable()) {
656 $mail->disabled
= true
;
657 $mail->active
= false
;
660 check_redirect($this);
663 // function enable() {{{2
665 public function enable()
667 XDB
::execute("UPDATE emails
669 WHERE flags = 'disable' AND uid = {?}", $this->user
->id());
670 foreach ($this->emails
as &$mail) {
671 if ($mail->disabled
) {
672 $mail->active
= true
;
673 $mail->disabled
= false
;
675 check_redirect($this);
679 // function get_broken_mx() {{{2
681 public function get_broken_mx()
683 $res = XDB
::query("SELECT host, text
685 WHERE state != 'ok'");
686 if (!$res->numRows()) {
689 $mxs = $res->fetchAllAssoc();
691 foreach ($this->emails
as &$mail) {
692 if ($mail->active
&& strstr($mail->email
, '@') !== false
) {
693 list(,$domain) = explode('@', $mail->email
);
694 getmxrr($domain, $lcl_mxs);
695 if (empty($lcl_mxs)) {
696 $lcl_mxs = array($domain);
699 foreach ($mxs as &$mx) {
700 foreach ($lcl_mxs as $lcl) {
701 if (fnmatch($mx['host'], $lcl)) {
702 $broken = $mx['text'];
707 $mails[] = array('mail' => $mail->email
, 'text' => $broken);
716 // function active_emails() {{{2
718 public function active_emails()
721 foreach ($this->emails
as $mail) {
729 // function get_uid() {{{2
731 public function get_uid()
733 return $this->user
->id();
737 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: