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 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 $count = XDB
::fetchOneCell('SELECT COUNT(*)
33 FROM email_source_account
34 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags)',
39 } elseif ($count > 1) {
40 // If too many bestaliases, delete the bestalias flag from all this
41 // user's emails (this should never happen).
42 XDB
::execute("UPDATE email_source_account
43 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
48 // If no bestalias is selected, we choose the shortest email which is not
49 // related to a usage name and contains a '.'.
50 XDB
::execute("UPDATE email_source_account
51 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
53 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
58 // function valide_email() {{{1
59 // Returns a cleaned-up version of the @p email string. It removes garbage
60 // characters, and determines the canonical form (without _ and +) for
61 // Polytechnique.org email addresses.
62 function valide_email($str)
66 $em = trim(rtrim($str));
67 $em = str_replace('<', '', $em);
68 $em = str_replace('>', '', $em);
69 if (strpos($em, '@') === false
) {
72 list($ident, $dom) = explode('@', $em);
73 if ($dom == $globals->mail
->domain ||
$dom == $globals->mail
->domain2
) {
74 list($ident1) = explode('_', $ident);
75 list($ident) = explode('+', $ident1);
77 return $ident . '@' . $dom;
80 // function isvalid_email_redirection() {{{1
81 /** Checks if an email is a suitable redirection.
82 * @param $email the email to check
85 function isvalid_email_redirection($email)
87 return isvalid_email($email) &&
88 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
91 // function ids_from_mails() {{{1
92 // Converts an array of emails to an array of email => uid, where email is the
93 // given email when we found a matching user.
94 function ids_from_mails(array $emails)
98 // Removes duplicates, if any.
99 $emails = array_unique($emails);
101 // Formats and splits by domain type (locally managed or external) emails.
102 $domain_emails = array();
103 $other_emails = array();
104 foreach ($emails as $email) {
105 if (strpos($email, '@') === false
) {
107 $domain = $globals->mail
->domain2
;
109 list($user, $domain) = explode('@', $email);
111 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
112 ||
$domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
113 list($user) = explode('+', $user);
114 list($user) = explode('_', $user);
115 $domain_emails[$email] = strtolower($user . '@' . $domain);
117 $other_emails[$email] = strtolower($user . '@' . $domain);
121 // Retrieves emails from our domains.
122 $domain_uids = XDB
::fetchAllAssoc('email',
124 FROM email_source_account
126 array_unique($domain_emails));
128 // Retrieves emails from redirections.
129 $other_uids = XDB
::fetchAllAssoc('redirect',
130 'SELECT redirect, uid
131 FROM email_redirect_account
132 WHERE redirect IN {?}',
133 array_unique($other_emails));
135 // Associates given emails with the corresponding uid.
137 foreach (array_merge($domain_emails, $other_emails) as $email => $canonical_email) {
138 if (array_key_exists($canonical_email, $domain_uids)) {
139 $uids[$email] = $domain_uids[$canonical_email];
140 } elseif (array_key_exists($canonical_email, $other_uids)) {
141 $uids[$email] = $other_uids[$canonical_email];
149 // The Bogo class represents a spam filtering level in plat/al architecture.
152 private static $states = array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
157 public function __construct(User
$user)
163 $this->user
= &$user;
164 $res = XDB
::query('SELECT action
165 FROM email_redirect_account
166 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
168 if ($res->numRows() == 0) {
171 $this->state
= $res->fetchOneCell();
174 public function change($state)
176 $this->state
= is_int($state) ? self
::$states[$state] : $state;
177 XDB
::execute('UPDATE email_redirect_account
179 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
180 $this->state
, $this->user
->id());
183 public function level()
185 return array_search($this->state
, self
::$states);
190 // Represents an "email address" used as final recipient for plat/al-managed
194 // Lists fields to load automatically.
195 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
197 // Shortname to realname mapping for known mail storage backends.
198 static private $display_names = array(
199 'imap' => 'Accès de secours aux emails (IMAP)',
200 'googleapps' => 'Compte Google Apps',
202 static private $storage_domains = array(
209 // Basic email properties; $sufficient indicates if the email can be used as
210 // an unique redirection; $redirect contains the delivery email address.
214 public $display_email;
218 // Redirection status properties.
224 public $allow_rewrite;
227 // Redirection bounces stats.
229 public $broken_level;
232 public function __construct(User
$user, array $row)
234 foreach (self
::$field_names as $field) {
235 if (array_key_exists($field, $row)) {
236 $this->$field = $row[$field];
239 $this->email
= $row['redirect'];
241 if (array_key_exists($this->type
, Email
::$display_names)) {
242 $this->display_email
= self
::$display_names[$this->type
];
244 $this->display_email
= $this->email
;
246 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
247 $this->$status = ($status == $row['flags']);
249 $this->sufficient
= ($this->type
== 'smtp' ||
$this->type
== 'googleapps');
250 $this->user
= &$user;
253 // Activates the email address as a redirection.
254 public function activate()
256 if ($this->inactive
) {
257 XDB
::execute('UPDATE email_redirect_account
258 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
259 WHERE uid = {?} AND redirect = {?}',
260 $this->user
->id(), $this->email
);
261 S
::logger()->log('email_on', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : ''));
262 $this->inactive
= false
;
263 $this->active
= true
;
267 // Deactivates the email address as a redirection.
268 public function deactivate()
271 XDB
::execute('UPDATE email_redirect_account
272 SET flags = \'inactive\'
273 WHERE uid = {?} AND redirect = {?}',
274 $this->user
->id(), $this->email
);
275 S
::logger()->log('email_off', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : "") );
276 $this->inactive
= true
;
277 $this->active
= false
;
282 // Sets the rewrite rule for the given address.
283 public function set_rewrite($rewrite)
285 if ($this->type
!= 'smtp' ||
$this->rewrite
== $rewrite) {
288 if (!$rewrite ||
!isvalid_email($rewrite)) {
291 XDB
::execute('UPDATE email_redirect_account
293 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
294 $rewrite, $this->user
->id(), $this->email
);
295 $this->rewrite
= $rewrite;
296 if (!$this->allow_rewrite
) {
298 if (empty($this->hash
)) {
299 $this->hash
= rand_url_id();
300 XDB
::execute('UPDATE email_redirect_account
302 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
303 $this->hash
, $this->user
->id(), $this->email
);
305 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
306 $mail->assign('mail', $this);
307 $mail->assign('user', $this->user
);
308 $mail->assign('baseurl', $globals->baseurl
);
309 $mail->assign('sitename', $globals->core
->sitename
);
310 $mail->assign('to', $this->email
);
311 $mail->send($this->user
->isEmailFormatHtml());
316 // Resets the error counts associated with the redirection.
317 public function clean_errors()
319 if ($this->type
!= 'smtp') {
326 $this->broken_level
= 0;
328 return XDB
::execute('UPDATE email_redirect_account
329 SET broken_level = 0, broken_date = 0, last = 0
330 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
331 $this->user
->id(), $this->email
);
335 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
336 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
337 // can be definitively removed; 'disable' indicates if the email has a third
338 // status 'disabled' in addition to 'active' and 'inactive').
339 public function has_rewrite()
341 return ($this->type
== 'smtp');
344 public function is_removable()
346 return ($this->type
== 'smtp');
349 public function has_disable()
354 public function is_redirection()
356 return ($this->type
== 'smtp');
359 // Returns the list of allowed storages for the @p user.
360 static private function get_allowed_storages(User
$user)
365 // Google Apps storage is available for users with valid Google Apps account.
366 require_once 'googleapps.inc.php';
367 if ($globals->mailstorage
->googleapps_domain
&&
368 GoogleAppsAccount
::account_status($user->id()) == 'active') {
369 $storages[] = 'googleapps';
372 // IMAP storage is always visible to administrators, and is allowed for
373 // everyone when the service is marked as 'active'.
374 if ($globals->mailstorage
->imap_active || S
::admin()) {
375 $storages[] = 'imap';
381 static public function activate_storage(User
$user, $storage)
383 Platal
::assert(in_array($storage, self
::get_allowed_storages($user)));
385 if (!self
::is_active_storage($user, $storage)) {
388 XDB
::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
389 VALUES ({?}, {?}, {?}, \'active\')',
390 $user->id(), $storage,
391 $user->hruid
. '@' . self
::$storage_domains[$storage] . '.' . $globals->mail
->domain
);
395 static public function deactivate_storage(User
$user, $storage)
397 if (in_array($storage, self
::$storage_domains)) {
398 XDB
::execute('DELETE FROM email_redirect_account
399 WHERE uid = {?} AND type = {?}',
400 $user->id(), $storage);
404 static public function is_active_storage(User
$user, $storage)
406 if (!in_array($storage, self
::$storage_domains)) {
409 $res = XDB
::fetchOneCell('SELECT COUNT(*)
410 FROM email_redirect_account
411 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
412 $user->id(), $storage);
413 return !is_null($res) && $res > 0;
416 // class Redirect {{{1
417 // Redirect is a placeholder class for an user's active redirections (third-party
418 // redirection email, or Polytechnique.org mail storages).
421 private $flags = 'active';
427 public function __construct(User
$user)
429 $this->user
= &$user;
430 $this->bogo
= new Bogo($user);
432 // Adds third-party email redirections.
433 $res = XDB
::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
434 FROM email_redirect_account
435 WHERE uid = {?} AND type != \'homonym\'',
437 $this->emails
= array();
438 while ($row = $res->next()) {
439 $this->emails
[] = new Email($user, $row);
443 public function other_active($email)
445 foreach ($this->emails
as $mail) {
446 if ($mail->email
!= $email && $mail->active
&& $mail->sufficient
) {
453 public function delete_email($email)
455 if (!$this->other_active($email)) {
456 return ERROR_INACTIVE_REDIRECTION
;
458 XDB
::execute('DELETE FROM email_redirect_account
459 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
460 $this->user
->id(), $email);
461 S
::logger()->log('email_del', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
462 foreach ($this->emails
as $i => $mail) {
463 if ($email == $mail->email
) {
464 unset($this->emails
[$i]);
467 check_redirect($this);
471 public function add_email($email)
473 $email_stripped = strtolower(trim($email));
474 if (!isvalid_email($email_stripped)) {
475 return ERROR_INVALID_EMAIL
;
477 if (!isvalid_email_redirection($email_stripped)) {
478 return ERROR_LOOP_EMAIL
;
480 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
481 XDB
::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
482 VALUES ({?}, {?}, \'active\')',
483 $this->user
->id(), $email);
484 if ($logger = S
::v('log', null
)) { // may be absent --> step4.php
485 S
::logger()->log('email_add', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
487 foreach ($this->emails
as $mail) {
488 if ($mail->email
== $email_stripped) {
492 $this->emails
[] = new Email($this->user
, array(
493 'redirect' => $email,
496 'action' => 'default',
497 'broken_date' => '0000-00-00',
499 'last' => '0000-00-00',
506 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user
->login());
507 check_redirect($this);
511 public function modify_email($emails_actifs, $emails_rewrite)
513 foreach ($this->emails
as &$email) {
514 if (in_array($email->email
, $emails_actifs)) {
517 $email->deactivate();
519 $email->set_rewrite($emails_rewrite[$email->email
]);
521 check_redirect($this);
525 public function modify_one_email($email, $activate)
529 foreach ($this->emails
as $i=>$mail) {
530 if ($mail->email
== $email) {
533 $allinactive &= !$mail->active ||
!$mail->sufficient ||
$mail->email
== $email;
535 if ($thisone === false
) {
536 return ERROR_INVALID_EMAIL
;
538 if ($allinactive ||
$activate) {
539 $this->emails
[$thisone]->activate();
541 $this->emails
[$thisone]->deactivate();
543 check_redirect($this);
544 if ($allinactive && !$activate) {
545 return ERROR_INACTIVE_REDIRECTION
;
550 public function modify_one_email_redirect($email, $redirect)
552 foreach ($this->emails
as &$mail) {
553 if ($mail->email
== $email) {
554 $mail->set_rewrite($redirect);
555 check_redirect($this);
561 public function clean_errors($email)
563 foreach ($this->emails
as &$mail) {
564 if ($mail->email
== $email) {
565 check_redirect($this);
566 return $mail->clean_errors();
572 public function disable()
574 XDB
::execute("UPDATE email_redirect_account
575 SET flags = 'disable'
576 WHERE flags = 'active' AND uid = {?}", $this->user
->id());
577 foreach ($this->emails
as &$mail) {
578 if ($mail->active
&& $mail->has_disable()) {
579 $mail->disabled
= true
;
580 $mail->active
= false
;
583 check_redirect($this);
586 public function enable()
588 XDB
::execute("UPDATE email_redirect_account
590 WHERE flags = 'disable' AND uid = {?}", $this->user
->id());
591 foreach ($this->emails
as &$mail) {
592 if ($mail->disabled
) {
593 $mail->disabled
= false
;
594 $mail->active
= true
;
596 check_redirect($this);
600 public function get_broken_mx()
602 $res = XDB
::query("SELECT host, text
604 WHERE state != 'ok'");
605 if (!$res->numRows()) {
608 $mxs = $res->fetchAllAssoc();
610 foreach ($this->emails
as &$mail) {
611 if ($mail->active
&& strstr($mail->email
, '@') !== false
) {
612 list(,$domain) = explode('@', $mail->email
);
613 getmxrr($domain, $lcl_mxs);
614 if (empty($lcl_mxs)) {
615 $lcl_mxs = array($domain);
618 foreach ($mxs as &$mx) {
619 foreach ($lcl_mxs as $lcl) {
620 if (fnmatch($mx['host'], $lcl)) {
621 $broken = $mx['text'];
626 $mails[] = array('mail' => $mail->email
, 'text' => $broken);
635 public function active_emails()
638 foreach ($this->emails
as $mail) {
646 public function get_uid()
648 return $this->user
->id();
652 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: