2 /***************************************************************************
3 * Copyright (C) 2003-2011 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 mark_broken_email() {{{1
28 function mark_broken_email($email, $admin = false
)
30 $email = valide_email($email);
31 if (empty($email) ||
$email == '@') {
35 $user = XDB
::fetchOneAssoc('SELECT r1.uid, r1.broken_level != 0 AS broken, a.hruid, COUNT(r2.uid) AS nb_mails, a.full_name, s.email AS alias
36 FROM email_redirect_account AS r1
37 INNER JOIN accounts AS a ON (a.uid = r1.uid)
38 INNER JOIN email_source_account AS s ON (a.uid = s.uid AND s.flags = \'bestalias\')
39 LEFT JOIN email_redirect_account AS r2 ON (a.uid = r2.uid AND r1.redirect != r2.redirect AND
40 r2.broken_level = 0 AND r2.flags = \'active\' AND
41 (r2.type = \'smtp\' OR r2.type = \'googleapps\'))
42 WHERE r1.redirect = {?}
43 GROUP BY r1.uid', $email);
46 // Mark address as broken.
47 if (!$user['broken']) {
48 XDB
::execute('UPDATE email_redirect_account
49 SET broken_date = NOW(), last = NOW(), broken_level = 1
50 WHERE redirect = {?}', $email);
52 XDB
::execute('UPDATE email_redirect_account
53 SET last = CURDATE(), broken_level = IF(broken_level > 1, 3, 2)
54 WHERE redirect = {?} AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
57 XDB
::execute('UPDATE email_redirect_account
59 WHERE redirect = {?} AND broken_level = 0', $email);
66 // function fix_bestalias() {{{1
67 // Checks for an existing 'bestalias' among the the current user's aliases, and
68 // eventually selects a new bestalias when required.
69 function fix_bestalias(User
$user)
71 $count = XDB
::fetchOneCell('SELECT COUNT(*)
72 FROM email_source_account
73 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags)',
78 } elseif ($count > 1) {
79 // If too many bestaliases, delete the bestalias flag from all this
80 // user's emails (this should never happen).
81 XDB
::execute("UPDATE email_source_account
82 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
87 // If no bestalias is selected, we choose the shortest email which is not
88 // related to a usage name and contains a '.'.
89 XDB
::execute("UPDATE email_source_account
90 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
92 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
97 // function valide_email() {{{1
98 // Returns a cleaned-up version of the @p email string. It removes garbage
99 // characters, and determines the canonical form (without _ and +) for
100 // Polytechnique.org email addresses.
101 function valide_email($str)
105 $em = trim(rtrim($str));
106 $em = str_replace('<', '', $em);
107 $em = str_replace('>', '', $em);
108 if (strpos($em, '@') === false
) {
111 list($ident, $dom) = explode('@', $em);
112 if ($dom == $globals->mail
->domain ||
$dom == $globals->mail
->domain2
) {
113 list($ident1) = explode('_', $ident);
114 list($ident) = explode('+', $ident1);
116 return $ident . '@' . $dom;
119 // function isvalid_email_redirection() {{{1
120 /** Checks if an email is a suitable redirection.
121 * @param $email the email to check
124 function isvalid_email_redirection($email)
126 return isvalid_email($email) &&
127 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
130 // function ids_from_mails() {{{1
131 // Converts an array of emails to an array of email => uid, where email is the
132 // given email when we found a matching user.
133 function ids_from_mails(array $emails)
137 // Removes duplicates, if any.
138 $emails = array_unique($emails);
140 // Formats and splits by domain type (locally managed or external) emails.
141 $domain_emails = array();
142 $other_emails = array();
143 foreach ($emails as $email) {
144 if (strpos($email, '@') === false
) {
146 $domain = $globals->mail
->domain2
;
148 list($user, $domain) = explode('@', $email);
150 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
151 ||
$domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
152 list($user) = explode('+', $user);
153 list($user) = explode('_', $user);
154 $domain_emails[$email] = strtolower($user . '@' . $domain);
156 $other_emails[$email] = strtolower($user . '@' . $domain);
160 // Retrieves emails from our domains.
161 $domain_uids = XDB
::fetchAllAssoc('email',
163 FROM email_source_account
165 array_unique($domain_emails));
167 // Retrieves emails from redirections.
168 $other_uids = XDB
::fetchAllAssoc('redirect',
169 'SELECT redirect, uid
170 FROM email_redirect_account
171 WHERE redirect IN {?}',
172 array_unique($other_emails));
174 // Associates given emails with the corresponding uid.
176 foreach (array_merge($domain_emails, $other_emails) as $email => $canonical_email) {
177 if (array_key_exists($canonical_email, $domain_uids)) {
178 $uids[$email] = $domain_uids[$canonical_email];
179 } elseif (array_key_exists($canonical_email, $other_uids)) {
180 $uids[$email] = $other_uids[$canonical_email];
188 // The Bogo class represents a spam filtering level in plat/al architecture.
191 private static $states = array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
196 public function __construct(User
$user)
202 $this->user
= &$user;
203 $res = XDB
::query('SELECT action
204 FROM email_redirect_account
205 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
207 if ($res->numRows() == 0) {
210 $this->state
= $res->fetchOneCell();
213 public function change($state)
215 $this->state
= is_int($state) ? self
::$states[$state] : $state;
216 XDB
::execute('UPDATE email_redirect_account
218 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
219 $this->state
, $this->user
->id());
222 public function level()
224 return array_search($this->state
, self
::$states);
229 // Represents an "email address" used as final recipient for plat/al-managed
233 // Lists fields to load automatically.
234 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
236 // Shortname to realname mapping for known mail storage backends.
237 static private $display_names = array(
238 'imap' => 'Accès de secours aux emails (IMAP)',
239 'googleapps' => 'Compte Google Apps',
241 static private $storage_domains = array(
248 // Basic email properties; $sufficient indicates if the email can be used as
249 // an unique redirection; $redirect contains the delivery email address.
253 public $display_email;
257 // Redirection status properties.
263 public $allow_rewrite;
266 // Redirection bounces stats.
268 public $broken_level;
271 public function __construct(User
$user, array $row)
273 foreach (self
::$field_names as $field) {
274 if (array_key_exists($field, $row)) {
275 $this->$field = $row[$field];
278 $this->email
= $row['redirect'];
280 if (array_key_exists($this->type
, Email
::$display_names)) {
281 $this->display_email
= self
::$display_names[$this->type
];
283 $this->display_email
= $this->email
;
285 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
286 $this->$status = ($status == $row['flags']);
288 $this->sufficient
= ($this->type
== 'smtp' ||
$this->type
== 'googleapps');
289 $this->user
= &$user;
292 // Activates the email address as a redirection.
293 public function activate()
295 if ($this->inactive
) {
296 XDB
::execute('UPDATE email_redirect_account
297 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
298 WHERE uid = {?} AND redirect = {?}',
299 $this->user
->id(), $this->email
);
300 S
::logger()->log('email_on', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : ''));
301 $this->inactive
= false
;
302 $this->active
= true
;
306 // Deactivates the email address as a redirection.
307 public function deactivate()
310 XDB
::execute('UPDATE email_redirect_account
311 SET flags = \'inactive\'
312 WHERE uid = {?} AND redirect = {?}',
313 $this->user
->id(), $this->email
);
314 S
::logger()->log('email_off', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : "") );
315 $this->inactive
= true
;
316 $this->active
= false
;
321 // Sets the rewrite rule for the given address.
322 public function set_rewrite($rewrite)
324 if ($this->type
!= 'smtp' ||
$this->rewrite
== $rewrite) {
327 if (!$rewrite ||
!isvalid_email($rewrite)) {
330 XDB
::execute('UPDATE email_redirect_account
332 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
333 $rewrite, $this->user
->id(), $this->email
);
334 $this->rewrite
= $rewrite;
335 if (!$this->allow_rewrite
) {
337 if (empty($this->hash
)) {
338 $this->hash
= rand_url_id();
339 XDB
::execute('UPDATE email_redirect_account
341 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
342 $this->hash
, $this->user
->id(), $this->email
);
344 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
345 $mail->assign('mail', $this);
346 $mail->assign('user', $this->user
);
347 $mail->assign('baseurl', $globals->baseurl
);
348 $mail->assign('sitename', $globals->core
->sitename
);
349 $mail->assign('to', $this->email
);
350 $mail->send($this->user
->isEmailFormatHtml());
355 // Resets the error counts associated with the redirection.
356 public function clean_errors()
358 if ($this->type
!= 'smtp') {
365 $this->broken_level
= 0;
367 return XDB
::execute('UPDATE email_redirect_account
368 SET broken_level = 0, broken_date = 0, last = 0
369 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
370 $this->user
->id(), $this->email
);
374 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
375 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
376 // can be definitively removed; 'disable' indicates if the email has a third
377 // status 'disabled' in addition to 'active' and 'inactive').
378 public function has_rewrite()
380 return ($this->type
== 'smtp');
383 public function is_removable()
385 return ($this->type
== 'smtp');
388 public function has_disable()
393 public function is_redirection()
395 return ($this->type
== 'smtp');
398 // Returns the list of allowed storages for the @p user.
399 static private function get_allowed_storages(User
$user)
404 // Google Apps storage is available for users with valid Google Apps account.
405 require_once 'googleapps.inc.php';
406 if ($globals->mailstorage
->googleapps_domain
&&
407 GoogleAppsAccount
::account_status($user->id()) == 'active') {
408 $storages[] = 'googleapps';
411 // IMAP storage is always visible to administrators, and is allowed for
412 // everyone when the service is marked as 'active'.
413 if ($globals->mailstorage
->imap_active || S
::admin()) {
414 $storages[] = 'imap';
420 static public function activate_storage(User
$user, $storage)
422 Platal
::assert(in_array($storage, self
::get_allowed_storages($user)));
424 if (!self
::is_active_storage($user, $storage)) {
427 XDB
::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
428 VALUES ({?}, {?}, {?}, \'active\')',
429 $user->id(), $storage,
430 $user->hruid
. '@' . self
::$storage_domains[$storage] . '.' . $globals->mail
->domain
);
434 static public function deactivate_storage(User
$user, $storage)
436 if (in_array($storage, self
::$storage_domains)) {
437 XDB
::execute('DELETE FROM email_redirect_account
438 WHERE uid = {?} AND type = {?}',
439 $user->id(), $storage);
443 static public function is_active_storage(User
$user, $storage)
445 if (!in_array($storage, self
::$storage_domains)) {
448 $res = XDB
::fetchOneCell('SELECT COUNT(*)
449 FROM email_redirect_account
450 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
451 $user->id(), $storage);
452 return !is_null($res) && $res > 0;
455 // class Redirect {{{1
456 // Redirect is a placeholder class for an user's active redirections (third-party
457 // redirection email, or Polytechnique.org mail storages).
460 private $flags = 'active';
466 public function __construct(User
$user)
468 $this->user
= &$user;
469 $this->bogo
= new Bogo($user);
471 // Adds third-party email redirections.
472 $res = XDB
::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
473 FROM email_redirect_account
474 WHERE uid = {?} AND type != \'homonym\'',
476 $this->emails
= array();
477 while ($row = $res->next()) {
478 $this->emails
[] = new Email($user, $row);
482 public function other_active($email)
484 foreach ($this->emails
as $mail) {
485 if ($mail->email
!= $email && $mail->active
&& $mail->sufficient
) {
492 public function delete_email($email)
494 if (!$this->other_active($email)) {
495 return ERROR_INACTIVE_REDIRECTION
;
497 XDB
::execute('DELETE FROM email_redirect_account
498 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
499 $this->user
->id(), $email);
500 S
::logger()->log('email_del', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
501 foreach ($this->emails
as $i => $mail) {
502 if ($email == $mail->email
) {
503 unset($this->emails
[$i]);
506 check_redirect($this);
510 public function add_email($email)
512 $email_stripped = strtolower(trim($email));
513 if (!isvalid_email($email_stripped)) {
514 return ERROR_INVALID_EMAIL
;
516 if (!isvalid_email_redirection($email_stripped)) {
517 return ERROR_LOOP_EMAIL
;
519 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
520 XDB
::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
521 VALUES ({?}, {?}, \'active\')',
522 $this->user
->id(), $email);
523 if ($logger = S
::v('log', null
)) { // may be absent --> step4.php
524 S
::logger()->log('email_add', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
526 foreach ($this->emails
as $mail) {
527 if ($mail->email
== $email_stripped) {
531 $this->emails
[] = new Email($this->user
, array(
532 'redirect' => $email,
535 'action' => 'default',
536 'broken_date' => '0000-00-00',
538 'last' => '0000-00-00',
545 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user
->login());
546 check_redirect($this);
550 public function modify_email($emails_actifs, $emails_rewrite)
552 foreach ($this->emails
as &$email) {
553 if (in_array($email->email
, $emails_actifs)) {
556 $email->deactivate();
558 $email->set_rewrite($emails_rewrite[$email->email
]);
560 check_redirect($this);
564 public function modify_one_email($email, $activate)
568 foreach ($this->emails
as $i=>$mail) {
569 if ($mail->email
== $email) {
572 $allinactive &= !$mail->active ||
!$mail->sufficient ||
$mail->email
== $email;
574 if ($thisone === false
) {
575 return ERROR_INVALID_EMAIL
;
577 if ($allinactive ||
$activate) {
578 $this->emails
[$thisone]->activate();
580 $this->emails
[$thisone]->deactivate();
582 check_redirect($this);
583 if ($allinactive && !$activate) {
584 return ERROR_INACTIVE_REDIRECTION
;
589 public function modify_one_email_redirect($email, $redirect)
591 foreach ($this->emails
as &$mail) {
592 if ($mail->email
== $email) {
593 $mail->set_rewrite($redirect);
594 check_redirect($this);
600 public function clean_errors($email)
602 foreach ($this->emails
as &$mail) {
603 if ($mail->email
== $email) {
604 check_redirect($this);
605 return $mail->clean_errors();
611 public function disable()
613 XDB
::execute("UPDATE email_redirect_account
614 SET flags = 'disable'
615 WHERE flags = 'active' AND uid = {?}", $this->user
->id());
616 foreach ($this->emails
as &$mail) {
617 if ($mail->active
&& $mail->has_disable()) {
618 $mail->disabled
= true
;
619 $mail->active
= false
;
622 check_redirect($this);
625 public function enable()
627 XDB
::execute("UPDATE email_redirect_account
629 WHERE flags = 'disable' AND uid = {?}", $this->user
->id());
630 foreach ($this->emails
as &$mail) {
631 if ($mail->disabled
) {
632 $mail->disabled
= false
;
633 $mail->active
= true
;
635 check_redirect($this);
639 public function get_broken_mx()
641 $res = XDB
::query("SELECT host, text
643 WHERE state != 'ok'");
644 if (!$res->numRows()) {
647 $mxs = $res->fetchAllAssoc();
649 foreach ($this->emails
as &$mail) {
650 if ($mail->active
&& strstr($mail->email
, '@') !== false
) {
651 list(,$domain) = explode('@', $mail->email
);
652 getmxrr($domain, $lcl_mxs);
653 if (empty($lcl_mxs)) {
654 $lcl_mxs = array($domain);
657 foreach ($mxs as &$mx) {
658 foreach ($lcl_mxs as $lcl) {
659 if (fnmatch($mx['host'], $lcl)) {
660 $broken = $mx['text'];
665 $mails[] = array('mail' => $mail->email
, 'text' => $broken);
674 public function active_emails()
677 foreach ($this->emails
as $mail) {
685 public function get_uid()
687 return $this->user
->id();
691 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: