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 ($dom == $globals->mail
->domain ||
$dom == $globals->mail
->domain2
) {
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) &&
235 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
238 // function ids_from_mails() {{{1
239 // Converts an array of emails to an array of email => uid, where email is the
240 // given email when we found a matching user.
241 function ids_from_mails(array $emails)
245 // Removes duplicates, if any.
246 $emails = array_unique($emails);
248 // Formats and splits by domain type (locally managed or external) emails.
249 $domain_emails = array();
250 $other_emails = array();
251 foreach ($emails as $email) {
252 if (strpos($email, '@') === false
) {
254 $domain = $globals->mail
->domain2
;
256 list($user, $domain) = explode('@', $email);
258 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
259 ||
$domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
260 list($user) = explode('+', $user);
261 list($user) = explode('_', $user);
262 $domain_emails[$email] = strtolower($user . '@' . $domain);
264 $other_emails[$email] = strtolower($user . '@' . $domain);
268 // Retrieves emails from our domains.
269 $domain_uids = XDB
::fetchAllAssoc('email',
271 FROM email_source_account
273 array_unique($domain_emails));
275 // Retrieves emails from redirections.
276 $other_uids = XDB
::fetchAllAssoc('redirect',
277 'SELECT redirect, uid
278 FROM email_redirect_account
279 WHERE redirect IN {?}',
280 array_unique($other_emails));
282 // Associates given emails with the corresponding uid.
284 foreach (array_merge($domain_emails, $other_emails) as $email => $canonical_email) {
285 if (array_key_exists($canonical_email, $domain_uids)) {
286 $uids[$email] = $domain_uids[$canonical_email];
287 } elseif (array_key_exists($canonical_email, $other_uids)) {
288 $uids[$email] = $other_uids[$canonical_email];
296 // The Bogo class represents a spam filtering level in plat/al architecture.
299 private static $states = array(
303 3 => 'tag_and_drop_spams',
309 public $single_state;
310 public $redirections;
311 public $single_redirection;
313 public function __construct(User
$user)
319 $this->user
= &$user;
320 $res = XDB
::fetchOneAssoc('SELECT COUNT(DISTINCT(action)) AS action_count, COUNT(redirect) AS redirect_count, action
321 FROM email_redirect_account
322 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\') AND flags = \'active\'',
324 if ($res['redirect_count'] == 0) {
328 $this->single_redirection
= ($res['redirect_count'] == 1);
329 $this->redirections
= XDB
::fetchAllAssoc('SELECT IF(type = \'googleapps\', type, redirect) AS redirect, type, action
330 FROM email_redirect_account
331 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')
332 ORDER BY type, redirect',
335 foreach ($this->redirections
AS &$redirection) {
336 $redirection['filter'] = array_search($redirection['action'], self
::$states);
338 if ($res['action_count'] == 1) {
339 $this->state
= array_search($res['action'], self
::$states);
340 $this->single_state
= true
;
342 $this->single_state
= $this->state
= false
;
346 public function changeAll($state)
348 Platal
::assert($state >= 0 && $state < count(self
::$states), 'Unknown antispam level.');
350 $this->state
= $state;
351 XDB
::execute('UPDATE email_redirect_account
353 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
354 self
::$states[$this->state
], $this->user
->id());
357 public function change($redirection, $state)
359 Platal
::assert($state >= 0 && $state < count(self
::$states), 'Unknown antispam level.');
361 XDB
::execute('UPDATE email_redirect_account
363 WHERE uid = {?} AND (type = {?} OR redirect = {?})',
364 self
::$states[$state], $this->user
->id(), $redirection, $redirection);
369 // Represents an "email address" used as final recipient for plat/al-managed
373 // Lists fields to load automatically.
374 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
376 // Shortname to realname mapping for known mail storage backends.
377 static private $display_names = array(
378 'imap' => 'Accès de secours aux emails (IMAP)',
379 'googleapps' => 'Compte Google Apps',
381 static private $storage_domains = array(
388 // Basic email properties; $sufficient indicates if the email can be used as
389 // an unique redirection; $redirect contains the delivery email address.
393 public $display_email;
397 // Redirection status properties.
403 public $allow_rewrite;
406 // Redirection bounces stats.
408 public $broken_level;
411 public function __construct(User
$user, array $row)
413 foreach (self
::$field_names as $field) {
414 if (array_key_exists($field, $row)) {
415 $this->$field = $row[$field];
418 $this->email
= $row['redirect'];
420 if (array_key_exists($this->type
, Email
::$display_names)) {
421 $this->display_email
= self
::$display_names[$this->type
];
423 $this->display_email
= $this->email
;
425 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
426 $this->$status = ($status == $row['flags']);
428 $this->sufficient
= ($this->type
== 'smtp' ||
$this->type
== 'googleapps');
429 $this->user
= &$user;
432 // Activates the email address as a redirection.
433 public function activate()
435 if ($this->inactive
) {
436 XDB
::execute('UPDATE email_redirect_account
437 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
438 WHERE uid = {?} AND redirect = {?}',
439 $this->user
->id(), $this->email
);
440 S
::logger()->log('email_on', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : ''));
441 $this->inactive
= false
;
442 $this->active
= true
;
446 // Deactivates the email address as a redirection.
447 public function deactivate()
450 XDB
::execute('UPDATE email_redirect_account
451 SET flags = \'inactive\'
452 WHERE uid = {?} AND redirect = {?}',
453 $this->user
->id(), $this->email
);
454 S
::logger()->log('email_off', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : "") );
455 $this->inactive
= true
;
456 $this->active
= false
;
461 // Sets the rewrite rule for the given address.
462 public function set_rewrite($rewrite)
464 if ($this->type
!= 'smtp' ||
$this->rewrite
== $rewrite) {
467 if (!$rewrite ||
!isvalid_email($rewrite)) {
470 XDB
::execute('UPDATE email_redirect_account
472 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
473 $rewrite, $this->user
->id(), $this->email
);
474 $this->rewrite
= $rewrite;
475 if (!$this->allow_rewrite
) {
477 if (empty($this->hash
)) {
478 $this->hash
= rand_url_id();
479 XDB
::execute('UPDATE email_redirect_account
481 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
482 $this->hash
, $this->user
->id(), $this->email
);
484 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
485 $mail->assign('mail', $this);
486 $mail->assign('user', $this->user
);
487 $mail->assign('baseurl', $globals->baseurl
);
488 $mail->assign('sitename', $globals->core
->sitename
);
489 $mail->assign('to', $this->email
);
490 $mail->send($this->user
->isEmailFormatHtml());
495 // Resets the error counts associated with the redirection.
496 public function clean_errors()
498 if ($this->type
!= 'smtp') {
505 $this->broken_level
= 0;
507 return XDB
::execute('UPDATE email_redirect_account
508 SET broken_level = 0, broken_date = 0, last = 0
509 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
510 $this->user
->id(), $this->email
);
514 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
515 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
516 // can be definitively removed; 'disable' indicates if the email has a third
517 // status 'disabled' in addition to 'active' and 'inactive').
518 public function has_rewrite()
520 return ($this->type
== 'smtp');
523 public function is_removable()
525 return ($this->type
== 'smtp');
528 public function has_disable()
533 public function is_redirection()
535 return ($this->type
== 'smtp');
538 // Returns the list of allowed storages for the @p user.
539 static private function get_allowed_storages(User
$user)
544 // Google Apps storage is available for users with valid Google Apps account.
545 require_once 'googleapps.inc.php';
546 if ($globals->mailstorage
->googleapps_domain
&&
547 GoogleAppsAccount
::account_status($user->id()) == 'active') {
548 $storages[] = 'googleapps';
551 // IMAP storage is always visible to administrators, and is allowed for
552 // everyone when the service is marked as 'active'.
553 if ($globals->mailstorage
->imap_active || S
::admin()) {
554 $storages[] = 'imap';
560 static public function activate_storage(User
$user, $storage)
562 Platal
::assert(in_array($storage, self
::get_allowed_storages($user)));
564 if (!self
::is_active_storage($user, $storage)) {
567 XDB
::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
568 VALUES ({?}, {?}, {?}, \'active\')',
569 $user->id(), $storage,
570 $user->hruid
. '@' . self
::$storage_domains[$storage] . '.' . $globals->mail
->domain
);
574 static public function deactivate_storage(User
$user, $storage)
576 if (in_array($storage, self
::$storage_domains)) {
577 XDB
::execute('DELETE FROM email_redirect_account
578 WHERE uid = {?} AND type = {?}',
579 $user->id(), $storage);
583 static public function is_active_storage(User
$user, $storage)
585 if (!in_array($storage, self
::$storage_domains)) {
588 $res = XDB
::fetchOneCell('SELECT COUNT(*)
589 FROM email_redirect_account
590 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
591 $user->id(), $storage);
592 return !is_null($res) && $res > 0;
595 // class Redirect {{{1
596 // Redirect is a placeholder class for an user's active redirections (third-party
597 // redirection email, or Polytechnique.org mail storages).
600 private $flags = 'active';
606 public function __construct(User
$user)
608 $this->user
= &$user;
609 $this->bogo
= new Bogo($user);
611 // Adds third-party email redirections.
612 $res = XDB
::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
613 FROM email_redirect_account
614 WHERE uid = {?} AND type != \'homonym\'',
616 $this->emails
= array();
617 while ($row = $res->next()) {
618 $this->emails
[] = new Email($user, $row);
622 public function other_active($email)
624 foreach ($this->emails
as $mail) {
625 if ($mail->email
!= $email && $mail->active
&& $mail->sufficient
) {
632 public function delete_email($email)
634 if (!$this->other_active($email)) {
635 return ERROR_INACTIVE_REDIRECTION
;
637 XDB
::execute('DELETE FROM email_redirect_account
638 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
639 $this->user
->id(), $email);
640 S
::logger()->log('email_del', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
641 foreach ($this->emails
as $i => $mail) {
642 if ($email == $mail->email
) {
643 unset($this->emails
[$i]);
646 check_redirect($this);
650 public function add_email($email)
652 $email_stripped = strtolower(trim($email));
653 if (!isvalid_email($email_stripped)) {
654 return ERROR_INVALID_EMAIL
;
656 if (!isvalid_email_redirection($email_stripped)) {
657 return ERROR_LOOP_EMAIL
;
659 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
660 XDB
::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
661 VALUES ({?}, {?}, \'active\')',
662 $this->user
->id(), $email);
663 if ($logger = S
::v('log', null
)) { // may be absent --> step4.php
664 S
::logger()->log('email_add', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
666 foreach ($this->emails
as $mail) {
667 if ($mail->email
== $email_stripped) {
671 $this->emails
[] = new Email($this->user
, array(
672 'redirect' => $email,
675 'action' => 'default',
676 'broken_date' => '0000-00-00',
678 'last' => '0000-00-00',
685 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user
->login());
686 check_redirect($this);
690 public function modify_email($emails_actifs, $emails_rewrite)
692 foreach ($this->emails
as &$email) {
693 if (in_array($email->email
, $emails_actifs)) {
696 $email->deactivate();
698 $email->set_rewrite($emails_rewrite[$email->email
]);
700 check_redirect($this);
704 public function modify_one_email($email, $activate)
708 foreach ($this->emails
as $i=>$mail) {
709 if ($mail->email
== $email) {
712 $allinactive &= !$mail->active ||
!$mail->sufficient ||
$mail->email
== $email;
714 if ($thisone === false
) {
715 return ERROR_INVALID_EMAIL
;
717 if ($allinactive ||
$activate) {
718 $this->emails
[$thisone]->activate();
720 $this->emails
[$thisone]->deactivate();
722 check_redirect($this);
723 if ($allinactive && !$activate) {
724 return ERROR_INACTIVE_REDIRECTION
;
729 public function modify_one_email_redirect($email, $redirect)
731 foreach ($this->emails
as &$mail) {
732 if ($mail->email
== $email) {
733 $mail->set_rewrite($redirect);
734 check_redirect($this);
740 public function clean_errors($email)
742 foreach ($this->emails
as &$mail) {
743 if ($mail->email
== $email) {
744 check_redirect($this);
745 return $mail->clean_errors();
751 public function disable()
753 XDB
::execute("UPDATE email_redirect_account
754 SET flags = 'disable'
755 WHERE flags = 'active' AND uid = {?}", $this->user
->id());
756 foreach ($this->emails
as &$mail) {
757 if ($mail->active
&& $mail->has_disable()) {
758 $mail->disabled
= true
;
759 $mail->active
= false
;
762 check_redirect($this);
765 public function enable()
767 XDB
::execute("UPDATE email_redirect_account
769 WHERE flags = 'disable' AND uid = {?}", $this->user
->id());
770 foreach ($this->emails
as &$mail) {
771 if ($mail->disabled
) {
772 $mail->disabled
= false
;
773 $mail->active
= true
;
775 check_redirect($this);
779 public function get_broken_mx()
781 $res = XDB
::query("SELECT host, text
783 WHERE state != 'ok'");
784 if (!$res->numRows()) {
787 $mxs = $res->fetchAllAssoc();
789 foreach ($this->emails
as &$mail) {
790 if ($mail->active
&& strstr($mail->email
, '@') !== false
) {
791 list(,$domain) = explode('@', $mail->email
);
792 getmxrr($domain, $lcl_mxs);
793 if (empty($lcl_mxs)) {
794 $lcl_mxs = array($domain);
797 foreach ($mxs as &$mx) {
798 foreach ($lcl_mxs as $lcl) {
799 if (fnmatch($mx['host'], $lcl)) {
800 $broken = $mx['text'];
805 $mails[] = array('mail' => $mail->email
, 'text' => $broken);
814 public function active_emails()
817 foreach ($this->emails
as $mail) {
825 public function get_uid()
827 return $this->user
->id();
831 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: