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 add_to_list_alias(User
$user, $local_part, $domain, $type = 'alias')
29 Platal
::assert($user !== null
);
31 XDB
::execute('INSERT IGNORE INTO email_virtual (email, domain, redirect, type)
32 SELECT {?}, id, {?}, {?}
33 FROM email_virtual_domains
35 $local_part, $user->forlifeEmail(), $type, $domain);
38 function delete_from_list_alias(User
$user, $local_part, $domain, $type = 'alias')
40 Platal
::assert($user !== null
);
42 XDB
::execute('DELETE v
43 FROM email_virtual AS v
44 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
45 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
46 WHERE v.email = {?} AND d.name = {?} AND v.redirect = {?} AND type = {?}',
47 $local_part, $domain, $user->forlifeEmail(), $type);
50 function update_list_alias(User
$user, $former_email, $local_part, $domain, $type = 'alias')
52 Platal
::assert($user !== null
);
54 XDB
::execute('UPDATE email_virtual AS v
55 INNER JOIN email_virtual_domains AS d ON (v.domain = d.id)
57 WHERE v.redirect = {?} AND d.name = {?} AND v.email = {?} AND v.type = {?}',
58 $user->forlifeEmail(), $former_email, $domain, $local_part, $type);
61 function list_alias_members($local_part, $domain)
63 $emails = XDB
::fetchColumn('SELECT DISTINCT(redirect)
64 FROM email_virtual AS v
65 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
66 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
67 WHERE v.email = {?} AND d.name = {?} AND type = \'alias\'',
68 $local_part, $domain);
71 foreach ($emails as $email) {
72 $members[] = User
::getSilent($email);
78 function delete_list_alias($local_part, $domain)
80 XDB
::execute('DELETE v
81 FROM email_virtual AS v
82 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
83 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
84 WHERE v.email = {?} AND d.name = {?} AND type = \'alias\'',
85 $local_part, $domain);
88 function iterate_list_alias($domain)
90 return XDB
::fetchColumn('SELECT CONCAT(v.email, \'@\', m.name)
91 FROM email_virtual AS v
92 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
93 WHERE m.name = {?} AND v.type = \'alias\'
98 function create_list($local_part, $domain)
102 $redirect = $domain . '_' . $local_part . '+';
103 foreach(array('post', 'owner', 'admin', 'bounces', 'unsubscribe') as $suffix) {
104 XDB
::execute('INSERT IGNORE INTO email_virtual (email, domain, redirect, type)
105 SELECT {?}, id, {?}, \'list\'
106 FROM email_virtual_domains
108 ($suffix == 'post') ?
$local_part : $local_part . '-' . $suffix,
109 $redirect . $suffix . '@' . $globals->lists
->redirect_domain
, $domain);
113 function delete_list($local_part, $domain)
117 $redirect = $domain . '_' . $local_part . '+';
118 foreach(array('post', 'owner', 'admin', 'bounces', 'unsubscribe') as $suffix) {
119 XDB
::execute('DELETE email_virtual
120 WHERE redirect = {?} AND type = \'list\'',
121 $redirect . $suffix . '@' . $globals->lists
->redirect_domain
);
125 function list_exist($local_part, $domain)
127 return XDB
::fetchOneCell('SELECT COUNT(*)
128 FROM email_virtual AS v
129 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
130 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
131 WHERE v.email = {?} AND d.name = {?}',
132 $local_part, $domain);
135 // function mark_broken_email() {{{1
136 function mark_broken_email($email, $admin = false
)
138 $email = valide_email($email);
139 if (empty($email) ||
$email == '@') {
143 $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
144 FROM email_redirect_account AS r1
145 INNER JOIN accounts AS a ON (a.uid = r1.uid)
146 INNER JOIN email_source_account AS s ON (a.uid = s.uid AND s.flags = \'bestalias\')
147 LEFT JOIN email_redirect_account AS r2 ON (a.uid = r2.uid AND r1.redirect != r2.redirect AND
148 r2.broken_level = 0 AND r2.flags = \'active\' AND
149 (r2.type = \'smtp\' OR r2.type = \'googleapps\'))
150 WHERE r1.redirect = {?}
151 GROUP BY r1.uid', $email);
154 // Mark address as broken.
155 if (!$user['broken']) {
156 XDB
::execute('UPDATE email_redirect_account
157 SET broken_date = NOW(), last = NOW(), broken_level = 1
158 WHERE redirect = {?}', $email);
160 XDB
::execute('UPDATE email_redirect_account
161 SET last = CURDATE(), broken_level = broken_level + 1
162 WHERE redirect = {?} AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
165 XDB
::execute('UPDATE email_redirect_account
167 WHERE redirect = {?} AND broken_level = 0', $email);
174 // function fix_bestalias() {{{1
175 // Checks for an existing 'bestalias' among the the current user's aliases, and
176 // eventually selects a new bestalias when required.
177 function fix_bestalias(User
$user)
179 $count = XDB
::fetchOneCell('SELECT COUNT(*)
180 FROM email_source_account
181 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags) AND expire IS NULL',
186 } elseif ($count > 1) {
187 // If too many bestaliases, delete the bestalias flag from all this
188 // user's emails (this should never happen).
189 XDB
::execute("UPDATE email_source_account
190 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
195 // If no bestalias is selected, we choose the shortest email which is not
196 // related to a usage name and contains a '.'.
197 XDB
::execute("UPDATE email_source_account
198 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
199 WHERE uid = {?} AND expire IS NULL
200 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
205 // function valide_email() {{{1
206 // Returns a cleaned-up version of the @p email string. It removes garbage
207 // characters, and determines the canonical form (without _ and +) for
208 // Polytechnique.org email addresses.
209 function valide_email($str)
213 $em = trim(rtrim($str));
214 $em = str_replace('<', '', $em);
215 $em = str_replace('>', '', $em);
216 if (strpos($em, '@') === false
) {
219 list($ident, $dom) = explode('@', $em);
220 if (User
::isMainMailDomain($dom)) {
221 list($ident1) = explode('_', $ident);
222 list($ident) = explode('+', $ident1);
224 return $ident . '@' . $dom;
227 // function isvalid_email_redirection() {{{1
228 /** Checks if an email is a suitable redirection.
229 * @param $email the email to check
232 function isvalid_email_redirection($email)
234 return isvalid_email($email) && !preg_match("/@polytechnique\.edu$/", $email) && User
::isForeignEmailAddress($email);
237 // function ids_from_mails() {{{1
238 // Converts an array of emails to an array of email => uid, where email is the
239 // given email when we found a matching user.
240 function ids_from_mails(array $emails)
242 // Removes duplicates, if any.
243 $emails = array_unique($emails);
245 // Formats and splits by domain type (locally managed or external) emails.
246 $main_domain_emails = array();
247 $aux_domain_emails = array();
248 $other_emails = array();
249 foreach ($emails as $email) {
250 if (strpos($email, '@') === false
) {
251 $main_domain_emails[] = $email;
253 if (User
::isForeignEmailAddress($email)) {
254 $other_emails[$email] = strtolower($user . '@' . $domain);
256 list($local_part, $domain) = explode('@', $email);
257 list($local_part) = explode('+', $local_part);
258 list($local_part) = explode('_', $local_part);
259 if (User
::isMainMailDomain($domain)) {
260 $main_domain_emails[$email] = strtolower($local_part);
261 } elseif (User
::isAliasMailDomain($domain)) {
262 $aux_domain_emails[$email] = strtolower($local_part);
268 // Retrieves emails from our domains.
269 $main_domain_uids = XDB
::fetchAllAssoc('email',
271 FROM email_source_account
272 WHERE email IN {?} AND type != \'alias_aux\'',
273 array_unique($main_domain_emails));
274 $aux_domain_uids = XDB
::fetchAllAssoc('email',
276 FROM email_source_account
277 WHERE email IN {?} AND type = \'alias_aux\'',
278 array_unique($aux_domain_emails));
280 // Retrieves emails from redirections.
281 $other_uids = XDB
::fetchAllAssoc('redirect',
282 'SELECT redirect, uid
283 FROM email_redirect_account
284 WHERE redirect IN {?}',
285 array_unique($other_emails));
287 // Associates given emails with the corresponding uid.
289 foreach ($main_domain_emails as $email => $key) {
290 $uids[$email] = $main_domain_uids[$key];
292 foreach ($aux_domain_emails as $email => $key) {
293 $uids[$email] = $aux_domain_uids[$key];
295 foreach ($other_emails as $email => $key) {
296 $uids[$email] = $other_uids[$key];
299 return array_unique($uids);
303 // The Bogo class represents a spam filtering level in plat/al architecture.
306 public static $states = array(
310 3 => 'tag_and_drop_spams',
316 public $single_state;
317 public $redirections;
318 public $single_redirection;
320 public function __construct(User
$user)
326 $this->user
= &$user;
327 $res = XDB
::fetchOneAssoc('SELECT COUNT(DISTINCT(action)) AS action_count, COUNT(redirect) AS redirect_count, action
328 FROM email_redirect_account
329 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\') AND flags = \'active\'',
331 if ($res['redirect_count'] == 0) {
335 $this->single_redirection
= ($res['redirect_count'] == 1);
336 $this->redirections
= XDB
::fetchAllAssoc('SELECT IF(type = \'googleapps\', type, redirect) AS redirect, type, action
337 FROM email_redirect_account
338 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')
339 ORDER BY type, redirect',
342 foreach ($this->redirections
AS &$redirection) {
343 $redirection['filter'] = array_search($redirection['action'], self
::$states);
345 if ($res['action_count'] == 1) {
346 $this->state
= array_search($res['action'], self
::$states);
347 $this->single_state
= true
;
349 $this->single_state
= $this->state
= false
;
353 public function changeAll($state)
355 Platal
::assert($state >= 0 && $state < count(self
::$states), 'Unknown antispam level.');
357 $this->state
= $state;
358 XDB
::execute('UPDATE email_redirect_account
360 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
361 self
::$states[$this->state
], $this->user
->id());
364 public function change($redirection, $state)
366 Platal
::assert($state >= 0 && $state < count(self
::$states), 'Unknown antispam level.');
368 XDB
::execute('UPDATE email_redirect_account
370 WHERE uid = {?} AND (type = {?} OR redirect = {?})',
371 self
::$states[$state], $this->user
->id(), $redirection, $redirection);
376 // Represents an "email address" used as final recipient for plat/al-managed
380 // Lists fields to load automatically.
381 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
383 // Shortname to realname mapping for known mail storage backends.
384 static private $display_names = array(
385 'imap' => 'Accès de secours aux emails (IMAP)',
386 'googleapps' => 'Compte Google Apps',
388 static private $storage_domains = array(
395 // Basic email properties; $sufficient indicates if the email can be used as
396 // an unique redirection; $redirect contains the delivery email address.
400 public $display_email;
403 public $filter_level;
405 // Redirection status properties.
411 public $allow_rewrite;
414 // Redirection bounces stats.
416 public $broken_level;
419 public function __construct(User
$user, array $row)
421 foreach (self
::$field_names as $field) {
422 if (array_key_exists($field, $row)) {
423 $this->$field = $row[$field];
426 $this->email
= $row['redirect'];
428 if (array_key_exists($this->type
, Email
::$display_names)) {
429 $this->display_email
= self
::$display_names[$this->type
];
431 $this->display_email
= $this->email
;
433 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
434 $this->$status = ($status == $row['flags']);
436 $this->sufficient
= ($this->type
== 'smtp' ||
$this->type
== 'googleapps');
437 $this->filter_level
= ($this->type
== 'imap') ? null
: array_search($this->action
, Bogo
::$states);
438 $this->user
= &$user;
441 // Activates the email address as a redirection.
442 public function activate()
444 if ($this->inactive
) {
445 XDB
::execute('UPDATE email_redirect_account
446 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
447 WHERE uid = {?} AND redirect = {?}',
448 $this->user
->id(), $this->email
);
449 S
::logger()->log('email_on', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : ''));
450 $this->inactive
= false
;
451 $this->active
= true
;
455 // Deactivates the email address as a redirection.
456 public function deactivate()
459 XDB
::execute('UPDATE email_redirect_account
460 SET flags = \'inactive\'
461 WHERE uid = {?} AND redirect = {?}',
462 $this->user
->id(), $this->email
);
463 S
::logger()->log('email_off', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : "") );
464 $this->inactive
= true
;
465 $this->active
= false
;
470 // Sets the rewrite rule for the given address.
471 public function set_rewrite($rewrite)
473 if ($this->type
!= 'smtp' ||
$this->rewrite
== $rewrite) {
476 if (!$rewrite ||
!isvalid_email($rewrite)) {
479 XDB
::execute('UPDATE email_redirect_account
481 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
482 $rewrite, $this->user
->id(), $this->email
);
483 $this->rewrite
= $rewrite;
484 if (!$this->allow_rewrite
) {
486 if (empty($this->hash
)) {
487 $this->hash
= rand_url_id();
488 XDB
::execute('UPDATE email_redirect_account
490 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
491 $this->hash
, $this->user
->id(), $this->email
);
493 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
494 $mail->assign('mail', $this);
495 $mail->assign('user', $this->user
);
496 $mail->assign('baseurl', $globals->baseurl
);
497 $mail->assign('sitename', $globals->core
->sitename
);
498 $mail->assign('to', $this->email
);
499 $mail->send($this->user
->isEmailFormatHtml());
504 // Resets the error counts associated with the redirection.
505 public function clean_errors()
507 if ($this->type
!= 'smtp') {
514 $this->broken_level
= 0;
516 return XDB
::execute('UPDATE email_redirect_account
517 SET broken_level = 0, broken_date = 0, last = 0
518 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
519 $this->user
->id(), $this->email
);
523 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
524 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
525 // can be definitively removed; 'disable' indicates if the email has a third
526 // status 'disabled' in addition to 'active' and 'inactive').
527 public function has_rewrite()
529 return ($this->type
== 'smtp');
532 public function is_removable()
534 return ($this->type
== 'smtp');
537 public function has_disable()
542 public function is_redirection()
544 return ($this->type
== 'smtp');
547 // Returns the list of allowed storages for the @p user.
548 static private function get_allowed_storages(User
$user)
553 // Google Apps storage is available for users with valid Google Apps account.
554 require_once 'googleapps.inc.php';
555 if ($globals->mailstorage
->googleapps_domain
&&
556 GoogleAppsAccount
::account_status($user->id()) == 'active') {
557 $storages[] = 'googleapps';
560 // IMAP storage is always visible to administrators, and is allowed for
561 // everyone when the service is marked as 'active'.
562 if ($globals->mailstorage
->imap_active || S
::admin()) {
563 $storages[] = 'imap';
569 static public function activate_storage(User
$user, $storage)
571 Platal
::assert(in_array($storage, self
::get_allowed_storages($user)));
573 if (!self
::is_active_storage($user, $storage)) {
576 XDB
::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
577 VALUES ({?}, {?}, {?}, \'active\')',
578 $user->id(), $storage,
579 $user->hruid
. '@' . self
::$storage_domains[$storage] . '.' . $globals->mail
->domain
);
583 static public function deactivate_storage(User
$user, $storage)
585 if (in_array($storage, self
::$storage_domains)) {
586 XDB
::execute('DELETE FROM email_redirect_account
587 WHERE uid = {?} AND type = {?}',
588 $user->id(), $storage);
592 static public function is_active_storage(User
$user, $storage)
594 if (!in_array($storage, self
::$storage_domains)) {
597 $res = XDB
::fetchOneCell('SELECT COUNT(*)
598 FROM email_redirect_account
599 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
600 $user->id(), $storage);
601 return !is_null($res) && $res > 0;
604 // class Redirect {{{1
605 // Redirect is a placeholder class for an user's active redirections (third-party
606 // redirection email, or Polytechnique.org mail storages).
609 private $flags = 'active';
615 public function __construct(User
$user)
617 $this->user
= &$user;
618 $this->bogo
= new Bogo($user);
620 // Adds third-party email redirections.
621 $res = XDB
::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
622 FROM email_redirect_account
623 WHERE uid = {?} AND type != \'homonym\'',
625 $this->emails
= array();
626 while ($row = $res->next()) {
627 $this->emails
[] = new Email($user, $row);
631 public function other_active($email)
633 foreach ($this->emails
as $mail) {
634 if ($mail->email
!= $email && $mail->active
&& $mail->sufficient
) {
641 public function delete_email($email)
643 if (!$this->other_active($email)) {
644 return ERROR_INACTIVE_REDIRECTION
;
646 XDB
::execute('DELETE FROM email_redirect_account
647 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
648 $this->user
->id(), $email);
649 S
::logger()->log('email_del', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
650 foreach ($this->emails
as $i => $mail) {
651 if ($email == $mail->email
) {
652 unset($this->emails
[$i]);
655 check_redirect($this);
659 public function add_email($email)
661 $email_stripped = strtolower(trim($email));
662 if (!isvalid_email($email_stripped)) {
663 return ERROR_INVALID_EMAIL
;
665 if (!isvalid_email_redirection($email_stripped)) {
666 return ERROR_LOOP_EMAIL
;
668 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
669 XDB
::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
670 VALUES ({?}, {?}, \'active\')',
671 $this->user
->id(), $email);
672 if ($logger = S
::v('log', null
)) { // may be absent --> step4.php
673 S
::logger()->log('email_add', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
675 foreach ($this->emails
as $mail) {
676 if ($mail->email
== $email_stripped) {
680 $this->emails
[] = new Email($this->user
, array(
681 'redirect' => $email,
684 'action' => 'default',
685 'broken_date' => '0000-00-00',
687 'last' => '0000-00-00',
694 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user
->login());
695 check_redirect($this);
699 public function modify_email($emails_actifs, $emails_rewrite)
701 foreach ($this->emails
as &$email) {
702 if (in_array($email->email
, $emails_actifs)) {
705 $email->deactivate();
707 $email->set_rewrite($emails_rewrite[$email->email
]);
709 check_redirect($this);
713 public function modify_one_email($email, $activate)
717 foreach ($this->emails
as $i=>$mail) {
718 if ($mail->email
== $email) {
721 $allinactive &= !$mail->active ||
!$mail->sufficient ||
$mail->email
== $email;
723 if ($thisone === false
) {
724 return ERROR_INVALID_EMAIL
;
726 if ($allinactive ||
$activate) {
727 $this->emails
[$thisone]->activate();
729 $this->emails
[$thisone]->deactivate();
731 check_redirect($this);
732 if ($allinactive && !$activate) {
733 return ERROR_INACTIVE_REDIRECTION
;
738 public function modify_one_email_redirect($email, $redirect)
740 foreach ($this->emails
as &$mail) {
741 if ($mail->email
== $email) {
742 $mail->set_rewrite($redirect);
743 check_redirect($this);
749 public function clean_errors($email)
751 foreach ($this->emails
as &$mail) {
752 if ($mail->email
== $email) {
753 check_redirect($this);
754 return $mail->clean_errors();
760 public function disable()
762 XDB
::execute("UPDATE email_redirect_account
763 SET flags = 'disable'
764 WHERE flags = 'active' AND uid = {?}", $this->user
->id());
765 foreach ($this->emails
as &$mail) {
766 if ($mail->active
&& $mail->has_disable()) {
767 $mail->disabled
= true
;
768 $mail->active
= false
;
771 check_redirect($this);
774 public function enable()
776 XDB
::execute("UPDATE email_redirect_account
778 WHERE flags = 'disable' AND uid = {?}", $this->user
->id());
779 foreach ($this->emails
as &$mail) {
780 if ($mail->disabled
) {
781 $mail->disabled
= false
;
782 $mail->active
= true
;
784 check_redirect($this);
788 public function get_broken_mx()
790 $res = XDB
::query("SELECT host, text
792 WHERE state != 'ok'");
793 if (!$res->numRows()) {
796 $mxs = $res->fetchAllAssoc();
798 foreach ($this->emails
as &$mail) {
799 if ($mail->active
&& strstr($mail->email
, '@') !== false
) {
800 list(,$domain) = explode('@', $mail->email
);
801 getmxrr($domain, $lcl_mxs);
802 if (empty($lcl_mxs)) {
803 $lcl_mxs = array($domain);
806 foreach ($mxs as &$mx) {
807 foreach ($lcl_mxs as $lcl) {
808 if (fnmatch($mx['host'], $lcl)) {
809 $broken = $mx['text'];
814 $mails[] = array('mail' => $mail->email
, 'text' => $broken);
823 public function active_emails()
826 foreach ($this->emails
as $mail) {
834 public function get_uid()
836 return $this->user
->id();
840 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: