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)
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)
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 list_alias_members($local_part, $domain)
52 $emails = XDB
::fetchColumn('SELECT DISTINCT(redirect)
53 FROM email_virtual AS v
54 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
55 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
56 WHERE v.email = {?} AND d.name = {?} AND type = \'user\'',
57 $local_part, $domain);
60 foreach ($emails as $email) {
61 $members[] = User
::getSilent($email);
67 function delete_list_alias($local_part, $domain)
69 XDB
::execute('DELETE v
70 FROM email_virtual AS v
71 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
72 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
73 WHERE v.email = {?} AND d.name = {?} AND type = \'user\'',
74 $local_part, $domain);
77 function iterate_list_alias($domain)
79 return XDB
::fetchColumn('SELECT CONCAT(v.email, \'@\', m.name)
80 FROM email_virtual AS v
81 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
82 WHERE m.name = {?} AND v.type = \'user\'
87 function create_list($local_part, $domain)
91 $redirect = $domain . '_' . $local_part . '+';
92 foreach(array('post', 'owner', 'admin', 'bounces', 'unsubscribe') as $suffix) {
93 XDB
::execute('INSERT IGNORE INTO email_virtual (email, domain, redirect, type)
94 SELECT {?}, id, {?}, \'list\'
95 FROM email_virtual_domains
97 ($suffix == 'post') ?
$local_part : $local_part . '-' . $suffix,
98 $redirect . $suffix . '@' . $globals->lists
->redirect_domain
, $domain);
102 function delete_list($local_part, $domain)
106 $redirect = $domain . '_' . $local_part . '+';
107 foreach(array('post', 'owner', 'admin', 'bounces', 'unsubscribe') as $suffix) {
108 XDB
::execute('DELETE email_virtual
109 WHERE redirect = {?} AND type = \'list\'',
110 $redirect . $suffix . '@' . $globals->lists
->redirect_domain
);
114 function list_exist($local_part, $domain)
116 return XDB
::fetchOneCell('SELECT COUNT(*)
117 FROM email_virtual AS v
118 INNER JOIN email_virtual_domains AS m ON (v.domain = m.id)
119 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
120 WHERE v.email = {?} AND d.name = {?}',
121 $local_part, $domain);
124 // function mark_broken_email() {{{1
125 function mark_broken_email($email, $admin = false
)
127 $email = valide_email($email);
128 if (empty($email) ||
$email == '@') {
132 $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
133 FROM email_redirect_account AS r1
134 INNER JOIN accounts AS a ON (a.uid = r1.uid)
135 INNER JOIN email_source_account AS s ON (a.uid = s.uid AND s.flags = \'bestalias\')
136 LEFT JOIN email_redirect_account AS r2 ON (a.uid = r2.uid AND r1.redirect != r2.redirect AND
137 r2.broken_level = 0 AND r2.flags = \'active\' AND
138 (r2.type = \'smtp\' OR r2.type = \'googleapps\'))
139 WHERE r1.redirect = {?}
140 GROUP BY r1.uid', $email);
143 // Mark address as broken.
144 if (!$user['broken']) {
145 XDB
::execute('UPDATE email_redirect_account
146 SET broken_date = NOW(), last = NOW(), broken_level = 1
147 WHERE redirect = {?}', $email);
149 XDB
::execute('UPDATE email_redirect_account
150 SET last = CURDATE(), broken_level = IF(broken_level > 1, 3, 2)
151 WHERE redirect = {?} AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
154 XDB
::execute('UPDATE email_redirect_account
156 WHERE redirect = {?} AND broken_level = 0', $email);
163 // function fix_bestalias() {{{1
164 // Checks for an existing 'bestalias' among the the current user's aliases, and
165 // eventually selects a new bestalias when required.
166 function fix_bestalias(User
$user)
168 $count = XDB
::fetchOneCell('SELECT COUNT(*)
169 FROM email_source_account
170 WHERE uid = {?} AND FIND_IN_SET(\'bestalias\', flags)',
175 } elseif ($count > 1) {
176 // If too many bestaliases, delete the bestalias flag from all this
177 // user's emails (this should never happen).
178 XDB
::execute("UPDATE email_source_account
179 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
184 // If no bestalias is selected, we choose the shortest email which is not
185 // related to a usage name and contains a '.'.
186 XDB
::execute("UPDATE email_source_account
187 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
189 ORDER BY NOT FIND_IN_SET('usage', flags), email LIKE '%.%', LENGTH(email)
194 // function valide_email() {{{1
195 // Returns a cleaned-up version of the @p email string. It removes garbage
196 // characters, and determines the canonical form (without _ and +) for
197 // Polytechnique.org email addresses.
198 function valide_email($str)
202 $em = trim(rtrim($str));
203 $em = str_replace('<', '', $em);
204 $em = str_replace('>', '', $em);
205 if (strpos($em, '@') === false
) {
208 list($ident, $dom) = explode('@', $em);
209 if ($dom == $globals->mail
->domain ||
$dom == $globals->mail
->domain2
) {
210 list($ident1) = explode('_', $ident);
211 list($ident) = explode('+', $ident1);
213 return $ident . '@' . $dom;
216 // function isvalid_email_redirection() {{{1
217 /** Checks if an email is a suitable redirection.
218 * @param $email the email to check
221 function isvalid_email_redirection($email)
223 return isvalid_email($email) &&
224 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
227 // function ids_from_mails() {{{1
228 // Converts an array of emails to an array of email => uid, where email is the
229 // given email when we found a matching user.
230 function ids_from_mails(array $emails)
234 // Removes duplicates, if any.
235 $emails = array_unique($emails);
237 // Formats and splits by domain type (locally managed or external) emails.
238 $domain_emails = array();
239 $other_emails = array();
240 foreach ($emails as $email) {
241 if (strpos($email, '@') === false
) {
243 $domain = $globals->mail
->domain2
;
245 list($user, $domain) = explode('@', $email);
247 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
248 ||
$domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
249 list($user) = explode('+', $user);
250 list($user) = explode('_', $user);
251 $domain_emails[$email] = strtolower($user . '@' . $domain);
253 $other_emails[$email] = strtolower($user . '@' . $domain);
257 // Retrieves emails from our domains.
258 $domain_uids = XDB
::fetchAllAssoc('email',
260 FROM email_source_account
262 array_unique($domain_emails));
264 // Retrieves emails from redirections.
265 $other_uids = XDB
::fetchAllAssoc('redirect',
266 'SELECT redirect, uid
267 FROM email_redirect_account
268 WHERE redirect IN {?}',
269 array_unique($other_emails));
271 // Associates given emails with the corresponding uid.
273 foreach (array_merge($domain_emails, $other_emails) as $email => $canonical_email) {
274 if (array_key_exists($canonical_email, $domain_uids)) {
275 $uids[$email] = $domain_uids[$canonical_email];
276 } elseif (array_key_exists($canonical_email, $other_uids)) {
277 $uids[$email] = $other_uids[$canonical_email];
285 // The Bogo class represents a spam filtering level in plat/al architecture.
288 private static $states = array('let_spams', 'tag_spams', 'tag_and_drop_spams', 'drop_spams');
293 public function __construct(User
$user)
299 $this->user
= &$user;
300 $res = XDB
::query('SELECT action
301 FROM email_redirect_account
302 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
304 if ($res->numRows() == 0) {
307 $this->state
= $res->fetchOneCell();
310 public function change($state)
312 $this->state
= is_int($state) ? self
::$states[$state] : $state;
313 XDB
::execute('UPDATE email_redirect_account
315 WHERE uid = {?} AND (type = \'smtp\' OR type = \'googleapps\')',
316 $this->state
, $this->user
->id());
319 public function level()
321 return array_search($this->state
, self
::$states);
326 // Represents an "email address" used as final recipient for plat/al-managed
330 // Lists fields to load automatically.
331 static private $field_names = array('rewrite', 'type', 'action', 'broken_date', 'broken_level', 'last', 'hash', 'allow_rewrite');
333 // Shortname to realname mapping for known mail storage backends.
334 static private $display_names = array(
335 'imap' => 'Accès de secours aux emails (IMAP)',
336 'googleapps' => 'Compte Google Apps',
338 static private $storage_domains = array(
345 // Basic email properties; $sufficient indicates if the email can be used as
346 // an unique redirection; $redirect contains the delivery email address.
350 public $display_email;
354 // Redirection status properties.
360 public $allow_rewrite;
363 // Redirection bounces stats.
365 public $broken_level;
368 public function __construct(User
$user, array $row)
370 foreach (self
::$field_names as $field) {
371 if (array_key_exists($field, $row)) {
372 $this->$field = $row[$field];
375 $this->email
= $row['redirect'];
377 if (array_key_exists($this->type
, Email
::$display_names)) {
378 $this->display_email
= self
::$display_names[$this->type
];
380 $this->display_email
= $this->email
;
382 foreach (array('active', 'inactive', 'broken', 'disabled') as $status) {
383 $this->$status = ($status == $row['flags']);
385 $this->sufficient
= ($this->type
== 'smtp' ||
$this->type
== 'googleapps');
386 $this->user
= &$user;
389 // Activates the email address as a redirection.
390 public function activate()
392 if ($this->inactive
) {
393 XDB
::execute('UPDATE email_redirect_account
394 SET broken_level = IF(flags = \'broken\', broken_level - 1, broken_level), flags = \'active\'
395 WHERE uid = {?} AND redirect = {?}',
396 $this->user
->id(), $this->email
);
397 S
::logger()->log('email_on', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : ''));
398 $this->inactive
= false
;
399 $this->active
= true
;
403 // Deactivates the email address as a redirection.
404 public function deactivate()
407 XDB
::execute('UPDATE email_redirect_account
408 SET flags = \'inactive\'
409 WHERE uid = {?} AND redirect = {?}',
410 $this->user
->id(), $this->email
);
411 S
::logger()->log('email_off', $this->email
. ($this->user
->id() != S
::v('uid') ?
"(admin on {$this->user->login()})" : "") );
412 $this->inactive
= true
;
413 $this->active
= false
;
418 // Sets the rewrite rule for the given address.
419 public function set_rewrite($rewrite)
421 if ($this->type
!= 'smtp' ||
$this->rewrite
== $rewrite) {
424 if (!$rewrite ||
!isvalid_email($rewrite)) {
427 XDB
::execute('UPDATE email_redirect_account
429 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
430 $rewrite, $this->user
->id(), $this->email
);
431 $this->rewrite
= $rewrite;
432 if (!$this->allow_rewrite
) {
434 if (empty($this->hash
)) {
435 $this->hash
= rand_url_id();
436 XDB
::execute('UPDATE email_redirect_account
438 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
439 $this->hash
, $this->user
->id(), $this->email
);
441 $mail = new PlMailer('emails/rewrite-in.mail.tpl');
442 $mail->assign('mail', $this);
443 $mail->assign('user', $this->user
);
444 $mail->assign('baseurl', $globals->baseurl
);
445 $mail->assign('sitename', $globals->core
->sitename
);
446 $mail->assign('to', $this->email
);
447 $mail->send($this->user
->isEmailFormatHtml());
452 // Resets the error counts associated with the redirection.
453 public function clean_errors()
455 if ($this->type
!= 'smtp') {
462 $this->broken_level
= 0;
464 return XDB
::execute('UPDATE email_redirect_account
465 SET broken_level = 0, broken_date = 0, last = 0
466 WHERE uid = {?} AND redirect = {?} AND type = \'smtp\'',
467 $this->user
->id(), $this->email
);
471 // Email backend capabilities ('rewrite' refers to From: rewrite for mails
472 // forwarded by Polytechnique.org's MXs; 'removable' indicates if the email
473 // can be definitively removed; 'disable' indicates if the email has a third
474 // status 'disabled' in addition to 'active' and 'inactive').
475 public function has_rewrite()
477 return ($this->type
== 'smtp');
480 public function is_removable()
482 return ($this->type
== 'smtp');
485 public function has_disable()
490 public function is_redirection()
492 return ($this->type
== 'smtp');
495 // Returns the list of allowed storages for the @p user.
496 static private function get_allowed_storages(User
$user)
501 // Google Apps storage is available for users with valid Google Apps account.
502 require_once 'googleapps.inc.php';
503 if ($globals->mailstorage
->googleapps_domain
&&
504 GoogleAppsAccount
::account_status($user->id()) == 'active') {
505 $storages[] = 'googleapps';
508 // IMAP storage is always visible to administrators, and is allowed for
509 // everyone when the service is marked as 'active'.
510 if ($globals->mailstorage
->imap_active || S
::admin()) {
511 $storages[] = 'imap';
517 static public function activate_storage(User
$user, $storage)
519 Platal
::assert(in_array($storage, self
::get_allowed_storages($user)));
521 if (!self
::is_active_storage($user, $storage)) {
524 XDB
::execute('INSERT INTO email_redirect_account (uid, type, redirect, flags)
525 VALUES ({?}, {?}, {?}, \'active\')',
526 $user->id(), $storage,
527 $user->hruid
. '@' . self
::$storage_domains[$storage] . '.' . $globals->mail
->domain
);
531 static public function deactivate_storage(User
$user, $storage)
533 if (in_array($storage, self
::$storage_domains)) {
534 XDB
::execute('DELETE FROM email_redirect_account
535 WHERE uid = {?} AND type = {?}',
536 $user->id(), $storage);
540 static public function is_active_storage(User
$user, $storage)
542 if (!in_array($storage, self
::$storage_domains)) {
545 $res = XDB
::fetchOneCell('SELECT COUNT(*)
546 FROM email_redirect_account
547 WHERE uid = {?} AND type = {?} AND flags = \'active\')',
548 $user->id(), $storage);
549 return !is_null($res) && $res > 0;
552 // class Redirect {{{1
553 // Redirect is a placeholder class for an user's active redirections (third-party
554 // redirection email, or Polytechnique.org mail storages).
557 private $flags = 'active';
563 public function __construct(User
$user)
565 $this->user
= &$user;
566 $this->bogo
= new Bogo($user);
568 // Adds third-party email redirections.
569 $res = XDB
::iterator('SELECT redirect, rewrite, type, action, broken_date, broken_level, last, flags, hash, allow_rewrite
570 FROM email_redirect_account
571 WHERE uid = {?} AND type != \'homonym\'',
573 $this->emails
= array();
574 while ($row = $res->next()) {
575 $this->emails
[] = new Email($user, $row);
579 public function other_active($email)
581 foreach ($this->emails
as $mail) {
582 if ($mail->email
!= $email && $mail->active
&& $mail->sufficient
) {
589 public function delete_email($email)
591 if (!$this->other_active($email)) {
592 return ERROR_INACTIVE_REDIRECTION
;
594 XDB
::execute('DELETE FROM email_redirect_account
595 WHERE uid = {?} AND redirect = {?} AND type != \'homonym\'',
596 $this->user
->id(), $email);
597 S
::logger()->log('email_del', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
598 foreach ($this->emails
as $i => $mail) {
599 if ($email == $mail->email
) {
600 unset($this->emails
[$i]);
603 check_redirect($this);
607 public function add_email($email)
609 $email_stripped = strtolower(trim($email));
610 if (!isvalid_email($email_stripped)) {
611 return ERROR_INVALID_EMAIL
;
613 if (!isvalid_email_redirection($email_stripped)) {
614 return ERROR_LOOP_EMAIL
;
616 // If the email was already present for this user, we reset it to the default values, we thus use REPLACE INTO.
617 XDB
::execute('REPLACE INTO email_redirect_account (uid, redirect, flags)
618 VALUES ({?}, {?}, \'active\')',
619 $this->user
->id(), $email);
620 if ($logger = S
::v('log', null
)) { // may be absent --> step4.php
621 S
::logger()->log('email_add', $email . ($this->user
->id() != S
::v('uid') ?
" (admin on {$this->user->login()})" : ""));
623 foreach ($this->emails
as $mail) {
624 if ($mail->email
== $email_stripped) {
628 $this->emails
[] = new Email($this->user
, array(
629 'redirect' => $email,
632 'action' => 'default',
633 'broken_date' => '0000-00-00',
635 'last' => '0000-00-00',
642 check_email($email, "Ajout d'une adresse surveillée aux redirections de " . $this->user
->login());
643 check_redirect($this);
647 public function modify_email($emails_actifs, $emails_rewrite)
649 foreach ($this->emails
as &$email) {
650 if (in_array($email->email
, $emails_actifs)) {
653 $email->deactivate();
655 $email->set_rewrite($emails_rewrite[$email->email
]);
657 check_redirect($this);
661 public function modify_one_email($email, $activate)
665 foreach ($this->emails
as $i=>$mail) {
666 if ($mail->email
== $email) {
669 $allinactive &= !$mail->active ||
!$mail->sufficient ||
$mail->email
== $email;
671 if ($thisone === false
) {
672 return ERROR_INVALID_EMAIL
;
674 if ($allinactive ||
$activate) {
675 $this->emails
[$thisone]->activate();
677 $this->emails
[$thisone]->deactivate();
679 check_redirect($this);
680 if ($allinactive && !$activate) {
681 return ERROR_INACTIVE_REDIRECTION
;
686 public function modify_one_email_redirect($email, $redirect)
688 foreach ($this->emails
as &$mail) {
689 if ($mail->email
== $email) {
690 $mail->set_rewrite($redirect);
691 check_redirect($this);
697 public function clean_errors($email)
699 foreach ($this->emails
as &$mail) {
700 if ($mail->email
== $email) {
701 check_redirect($this);
702 return $mail->clean_errors();
708 public function disable()
710 XDB
::execute("UPDATE email_redirect_account
711 SET flags = 'disable'
712 WHERE flags = 'active' AND uid = {?}", $this->user
->id());
713 foreach ($this->emails
as &$mail) {
714 if ($mail->active
&& $mail->has_disable()) {
715 $mail->disabled
= true
;
716 $mail->active
= false
;
719 check_redirect($this);
722 public function enable()
724 XDB
::execute("UPDATE email_redirect_account
726 WHERE flags = 'disable' AND uid = {?}", $this->user
->id());
727 foreach ($this->emails
as &$mail) {
728 if ($mail->disabled
) {
729 $mail->disabled
= false
;
730 $mail->active
= true
;
732 check_redirect($this);
736 public function get_broken_mx()
738 $res = XDB
::query("SELECT host, text
740 WHERE state != 'ok'");
741 if (!$res->numRows()) {
744 $mxs = $res->fetchAllAssoc();
746 foreach ($this->emails
as &$mail) {
747 if ($mail->active
&& strstr($mail->email
, '@') !== false
) {
748 list(,$domain) = explode('@', $mail->email
);
749 getmxrr($domain, $lcl_mxs);
750 if (empty($lcl_mxs)) {
751 $lcl_mxs = array($domain);
754 foreach ($mxs as &$mx) {
755 foreach ($lcl_mxs as $lcl) {
756 if (fnmatch($mx['host'], $lcl)) {
757 $broken = $mx['text'];
762 $mails[] = array('mail' => $mail->email
, 'text' => $broken);
771 public function active_emails()
774 foreach ($this->emails
as $mail) {
782 public function get_uid()
784 return $this->user
->id();
788 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: