Implements best_domain (Closes #1404).
[platal.git] / modules / email.php
CommitLineData
81b5b746 1<?php
2/***************************************************************************
12262f13 3 * Copyright (C) 2003-2011 Polytechnique.org *
81b5b746 4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22class EmailModule extends PLModule
23{
81b5b746 24 function handlers()
25 {
26 return array(
2914271e
FB
27 'emails' => $this->make_hook('emails', AUTH_COOKIE, 'mail'),
28 'emails/alias' => $this->make_hook('alias', AUTH_MDP, 'mail'),
29 'emails/antispam' => $this->make_hook('antispam', AUTH_MDP, 'mail'),
eb5a266d 30 'emails/broken' => $this->make_hook('broken', AUTH_COOKIE),
2914271e
FB
31 'emails/redirect' => $this->make_hook('redirect', AUTH_MDP, 'mail'),
32 'emails/send' => $this->make_hook('send', AUTH_MDP, 'mail'),
eb5a266d 33 'emails/antispam/submit' => $this->make_hook('submit', AUTH_COOKIE),
2914271e 34 'emails/test' => $this->make_hook('test', AUTH_COOKIE, 'mail', NO_AUTH),
9e570fe0 35
eb5a266d
SJ
36 'emails/rewrite/in' => $this->make_hook('rewrite_in', AUTH_PUBLIC),
37 'emails/rewrite/out' => $this->make_hook('rewrite_out', AUTH_PUBLIC),
3d17e48f 38
eb5a266d 39 'emails/imap/in' => $this->make_hook('imap_in', AUTH_PUBLIC),
2ee43273 40
eb5a266d
SJ
41 'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
42 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
43 'admin/emails/lost' => $this->make_hook('lost', AUTH_MDP, 'admin'),
67e06366 44 'admin/emails/broken' => $this->make_hook('broken_addr', AUTH_MDP, 'admin'),
81b5b746 45 );
46 }
47
26ba053e 48 function handler_emails($page, $action = null, $email = null)
81b5b746 49 {
50 global $globals;
e97e9b8f 51 require_once 'emails.inc.php';
81b5b746 52
53 $page->changeTpl('emails/index.tpl');
46f272fe 54 $page->setTitle('Mes emails');
81b5b746 55
2d997414 56 $user = S::user();
81b5b746 57
2d997414 58 // Apply the bestalias change request.
b7582015 59 if ($action == 'best' && $email) {
46504fb3
VZ
60 if (!S::has_xsrf_token()) {
61 return PL_FORBIDDEN;
62 }
63
b4503762
SJ
64 // First delete the bestalias flag from all this user's emails.
65 XDB::execute("UPDATE email_source_account
2d997414 66 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
fe13bc1d 67 WHERE uid = {?}", $user->id());
b4503762
SJ
68 // Then gives the bestalias flag to the given email.
69 list($email, $domain) = explode('@', $email);
70 XDB::execute("UPDATE email_source_account AS s
71 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
72 SET s.flags = CONCAT_WS(',', IF(s.flags = '', NULL, s.flags), 'bestalias')
73 WHERE s.uid = {?} AND s.email = {?} AND d.name = {?}", $user->id(), $email, $domain);
9f3f87bc
SJ
74 XDB::execute('UPDATE accounts AS a
75 INNER JOIN email_virtual_domains AS d ON (d.name = {?})
76 SET a.best_domain = d.id
77 WHERE a.uid = {?}',
78 $domain, $user->id());
2d997414
VZ
79
80 // As having a non-null bestalias value is critical in
81 // plat/al's code, we do an a posteriori check on the
82 // validity of the bestalias.
83 fix_bestalias($user);
81b5b746 84 }
85
2d997414 86 // Fetch and display aliases.
b4503762 87 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
9f3f87bc
SJ
88 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year, s.expire,
89 (FIND_IN_SET('bestalias', s.flags) AND a.best_domain = d.id) AS bestalias,
90 ((s.type = 'alias_aux') AND d.aliasing = d.id) AS alias
b4503762 91 FROM email_source_account AS s
9f3f87bc
SJ
92 INNER JOIN accounts AS a ON (s.uid = a.uid)
93 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
94 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
b4503762
SJ
95 WHERE s.uid = {?}
96 ORDER BY !alias, s.email",
08d33afc 97 $user->id());
b4503762
SJ
98 $page->assign('aliases', $aliases);
99
08d33afc
SJ
100 $alias = XDB::fetchOneCell('SELECT COUNT(email)
101 FROM email_source_account
102 WHERE uid = {?} AND type = \'alias_aux\'',
103 $user->id());
b4503762
SJ
104 $page->assign('alias', $alias);
105
81b5b746 106
2d997414 107 // Check for homonyms.
777c5910 108 $page->assign('homonyme', $user->homonyme);
e1547442 109
2d997414
VZ
110 // Display active redirections.
111 $redirect = new Redirect($user);
e97e9b8f 112 $page->assign('mails', $redirect->active_emails());
f036c896
SJ
113
114 // User's mail domains.
115 $mail_domains = array($user->alternateEmailDomain());
116 $mail_domains[] = User::$sub_mail_domains['all'] . $globals->mail->domain;
117 $mail_domains[] = User::$sub_mail_domains['all'] . $globals->mail->domain2;
118 $page->assign('main_email_domain', $user->mainEmailDomain());
119 $page->assign('mail_domains', $mail_domains);
81b5b746 120 }
121
26ba053e 122 function handler_alias($page, $action = null, $value = null)
81b5b746 123 {
81b5b746 124 global $globals;
125
126 $page->changeTpl('emails/alias.tpl');
46f272fe 127 $page->setTitle('Alias melix.net');
81b5b746 128
2d997414 129 $user = S::user();
b4503762 130 $page->assign('request', AliasReq::get_request($user->id()));
81b5b746 131
2d997414 132 // Remove the email alias.
b4503762 133 if ($action == 'delete') {
40d428d8
VZ
134 S::assert_xsrf_token();
135
08d33afc
SJ
136 XDB::execute('DELETE FROM email_source_account
137 WHERE uid = {?} AND type = \'alias_aux\'',
138 $user->id());
b4503762
SJ
139
140 require_once 'emails.inc.php';
141 fix_bestalias($user);
81b5b746 142 }
143
08d33afc 144 // Fetch existing auxiliary aliases.
b4503762
SJ
145 list($alias, $old_alias) = XDB::fetchOneRow('SELECT CONCAT(s.email, \'@\', d.name), s.email
146 FROM email_source_account AS s
147 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
08d33afc
SJ
148 WHERE s.uid = {?} AND s.type = \'alias_aux\'',
149 $user->id());
b4503762
SJ
150 $visibility = $user->hasProfile() && ($user->profile(true)->alias_pub == 'public');
151 $page->assign('current', $alias);
5b6768e6
FB
152 $page->assign('user', $user);
153 $page->assign('mail_public', $visibility);
81b5b746 154
b4503762 155 if ($action == 'ask' && Env::has('alias') && Env::has('reason')) {
40d428d8 156 S::assert_xsrf_token();
81b5b746 157
b4503762
SJ
158 // Retrieves user request.
159 $new_alias = Env::v('alias');
160 $reason = Env::v('reason');
6a4f0f01 161 $public = (Env::v('public', 'off') == 'on') ? 'public' : 'private';
81b5b746 162
b4503762
SJ
163 $page->assign('r_alias', $new_alias);
164 $page->assign('r_reason', $reason);
81b5b746 165 if ($public == 'public') {
166 $page->assign('r_public', true);
167 }
168
b4503762
SJ
169 // Checks special charaters in alias.
170 if (!preg_match("/^[a-zA-Z0-9\-.]{3,20}$/", $new_alias)) {
a7d35093
FB
171 $page->trigError("L'adresse demandée n'est pas valide."
172 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
173 . " et qu'elle ne contient que des lettres non accentuées,"
174 . " des chiffres ou les caractères - et .");
fd8f77de 175 return;
81b5b746 176 } else {
b4503762 177 // Checks if the alias has already been given.
08d33afc
SJ
178 $res = XDB::query('SELECT COUNT(email)
179 FROM email_source_account
180 WHERE email = {?} AND type = \'alias_aux\'',
181 $new_alias);
81b5b746 182 if ($res->fetchOneCell() > 0) {
b4503762 183 $page->trigError("L'alias $new_alias a déja été attribué. Tu ne peux donc pas l'obtenir.");
fd8f77de 184 return;
81b5b746 185 }
186
b4503762 187 // Checks if the alias has already been asked for.
7b094a73 188 $it = Validate::iterate('alias');
81b5b746 189 while($req = $it->next()) {
b4503762
SJ
190 if ($req->alias == $new_alias) {
191 $page->trigError("L'alias $new_alias a déja été demandé. Tu ne peux donc pas l'obtenir pour l'instant.");
192 return;
81b5b746 193 }
194 }
195
b4503762
SJ
196 // Sends requests. This will erase any previous alias pending request.
197 $myalias = new AliasReq($user, $new_alias, $reason, $public, $old_alias);
81b5b746 198 $myalias->submit();
b4503762 199 $page->assign('success', $new_alias);
fd8f77de 200 return;
81b5b746 201 }
46504fb3
VZ
202 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
203 if (!S::has_xsrf_token()) {
204 return PL_FORBIDDEN;
205 }
206
3e53a496 207 if ($user->hasProfile()) {
b4503762 208 XDB::execute('UPDATE profiles
3e53a496 209 SET alias_pub = {?}
b4503762 210 WHERE pid = {?}',
3e53a496 211 $value, $user->profile()->id());
81b5b746 212 }
8446dbd3 213 exit;
81b5b746 214 }
81b5b746 215 }
216
b4503762 217 function handler_redirect($page, $action = null, $email = null, $rewrite = null)
81b5b746 218 {
219 global $globals;
81b5b746 220 require_once 'emails.inc.php';
221
222 $page->changeTpl('emails/redirect.tpl');
223
2d997414
VZ
224 $user = S::user();
225 $page->assign_by_ref('user', $user);
226 $page->assign('eleve', $user->promo() >= date("Y") - 5);
3b83212e 227
2d997414 228 $redirect = new Redirect($user);
81b5b746 229
6d6b65bf 230 // FS#703 : $_GET is urldecoded twice, hence
231 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
232 // Since there can be no spaces in emails, we can fix this with :
233 $email = str_replace(' ', '+', $email);
234
2d997414 235 // Apply email redirection change requests.
1060c854 236 $result = SUCCESS;
81b5b746 237 if ($action == 'remove' && $email) {
1060c854 238 $result = $redirect->delete_email($email);
81b5b746 239 }
e1547442
FB
240
241 if ($action == 'active' && $email) {
242 $redirect->modify_one_email($email, true);
243 }
244
245 if ($action == 'inactive' && $email) {
246 $redirect->modify_one_email($email, false);
247 }
248
249 if ($action == 'rewrite' && $email) {
e1547442
FB
250 $redirect->modify_one_email_redirect($email, $rewrite);
251 }
252
40d428d8
VZ
253 if (Env::has('emailop')) {
254 S::assert_xsrf_token();
255
b4503762 256 $actifs = Env::v('emails_actifs', array());
5e2307dc 257 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
0fbd1f3f 258 $error_email = false;
b715c1e1 259 $new_email = Env::v('email');
6ea6d9c1 260 if ($new_email == "new@example.org") {
b715c1e1
SJ
261 $new_email = Env::v('email_new');
262 }
aef0283b
VZ
263 $result = $redirect->add_email($new_email);
264 if ($result == ERROR_INVALID_EMAIL) {
0fbd1f3f 265 $error_email = true;
b715c1e1
SJ
266 $page->assign('email', $new_email);
267 }
aef0283b 268 $page->assign('retour', $result);
0fbd1f3f 269 $page->assign('error_email', $error_email);
81b5b746 270 } elseif (empty($actifs)) {
1060c854 271 $result = ERROR_INACTIVE_REDIRECTION;
81b5b746 272 } elseif (is_array($actifs)) {
b4503762 273 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', array()));
81b5b746 274 }
275 }
276
1060c854 277 switch ($result) {
44b071c2
SJ
278 case ERROR_INACTIVE_REDIRECTION:
279 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
4478f95e 280 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
44b071c2
SJ
281 break;
282 case ERROR_INVALID_EMAIL:
0fbd1f3f 283 $page->trigError('Erreur : l\'email n\'est pas valide.');
44b071c2
SJ
284 break;
285 case ERROR_LOOP_EMAIL:
4478f95e 286 $page->trigError('Erreur : ' . $user->forlifeEmail()
44b071c2
SJ
287 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
288 . $globals->mail->domain2 . ' ni vers polytechnique.edu.');
289 break;
290 }
2d997414 291 // Fetch existing email aliases.
b4503762
SJ
292 $alias = XDB::query('SELECT CONCAT(s.email, \'@\', d.name) AS email, s.expire
293 FROM email_source_account AS s
294 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
295 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
296 WHERE s.uid = {?}
08d33afc
SJ
297 ORDER BY NOT(s.type = \'alias_aux\'), s.email, d.name',
298 $user->id());
b4503762
SJ
299 $page->assign('alias', $alias->fetchAllAssoc());
300
2d997414 301 $page->assign('emails', $redirect->emails);
aab4661d 302
2d997414 303 // Display GoogleApps acount information.
f5c4bf30 304 require_once 'googleapps.inc.php';
2d997414 305 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
b715c1e1
SJ
306
307 require_once 'emails.combobox.inc.php';
308 fill_email_combobox($page);
81b5b746 309 }
310
3b346b99 311 function handler_antispam($page, $filter_status = null, $redirection = null)
81b5b746 312 {
313 require_once 'emails.inc.php';
8f201b69
FB
314 $wp = new PlWikiPage('Xorg.Antispam');
315 $wp->buildCache();
81b5b746 316
317 $page->changeTpl('emails/antispam.tpl');
318
ea280814
SJ
319 $user = S::user();
320 $bogo = new Bogo($user);
3b346b99
SJ
321 if (!is_null($filter_status)) {
322 if (is_null($redirection)) {
323 $bogo->changeAll($filter_status);
324 } else {
325 $bogo->change($redirection, $filter_status);
326 }
81b5b746 327 }
3b346b99
SJ
328 $page->assign('filter', $bogo->state);
329 $page->assign('single_state', $bogo->single_state);
330 $page->assign('single_redirection', $bogo->single_redirection);
331 $page->assign('redirections', $bogo->redirections);
81b5b746 332 }
333
26ba053e 334 function handler_submit($page)
62ce6356 335 {
8f201b69
FB
336 $wp = new PlWikiPage('Xorg.Mails');
337 $wp->buildCache();
62ce6356 338 $page->changeTpl('emails/submit_spam.tpl');
339
40d428d8
VZ
340 if (Post::has('send_email')) {
341 S::assert_xsrf_token();
342
f3df6d38 343 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
15603084 344 if (!$upload) {
a7d35093 345 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
62ce6356 346 return;
347 }
15603084 348 $mime = $upload->contentType();
62ce6356 349 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
15603084 350 $upload->clear();
faefdbb7 351 $page->trigError('Le fichier ne contient pas un email complet');
62ce6356 352 return;
353 }
2d997414
VZ
354 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
355
62ce6356 356 global $globals;
2d997414 357 $box = $type . '@' . $globals->mail->domain;
62ce6356 358 $mailer = new PlMailer();
359 $mailer->addTo($box);
2d997414
VZ
360 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
361 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
362 $mailer->addUploadAttachment($upload, $type . '.mail');
62ce6356 363 $mailer->send();
a7d35093 364 $page->trigSuccess('Le message a été transmis à ' . $box);
15603084 365 $upload->clear();
62ce6356 366 }
367 }
368
26ba053e 369 function handler_send($page)
81b5b746 370 {
81b5b746 371 $page->changeTpl('emails/send.tpl');
372
46f272fe 373 $page->setTitle('Envoyer un email');
81b5b746 374
375 // action si on recoit un formulaire
3360c04f 376 if (Post::has('save')) {
46504fb3
VZ
377 if (!S::has_xsrf_token()) {
378 return PL_FORBIDDEN;
379 }
380
3360c04f
FB
381 unset($_POST['save']);
382 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
ed06daba
FB
383 Post::set('to_contacts', explode(';', Post::s('to_contacts')));
384 Post::set('cc_contacts', explode(';', Post::s('cc_contacts')));
3360c04f 385 $data = serialize($_POST);
00ba8a74
SJ
386 XDB::execute('INSERT INTO email_send_save (uid, data)
387 VALUES ({?}, {?})
388 ON DUPLICATE KEY UPDATE data = VALUES(data)',
48e683dd 389 S::user()->id('uid'), $data);
3360c04f
FB
390 }
391 exit;
40d428d8
VZ
392 } else if (Env::v('submit') == 'Envoyer') {
393 S::assert_xsrf_token();
394
91a14f73 395 function getEmails($aliases)
396 {
397 if (!is_array($aliases)) {
398 return null;
399 }
2d5264c6
FB
400 $uf = new UserFilter(new UFC_Hrpid($aliases));
401 $users = $uf->iterUsers();
91a14f73 402 $ret = array();
2d5264c6
FB
403 while ($user = $users->next()) {
404 $ret[] = $user->forlife;
91a14f73 405 }
406 return join(', ', $ret);
407 }
408
5e68682e 409 $error = false;
da419622 410 foreach ($_FILES as &$file) {
f3df6d38 411 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 412 $page->trigError(PlUpload::$lastError);
5e68682e
FB
413 $error = true;
414 break;
da419622 415 }
416 }
417
5e68682e
FB
418 if (!$error) {
419 XDB::execute("DELETE FROM email_send_save
48e683dd
FB
420 WHERE uid = {?}",
421 S::user()->id());
5e68682e
FB
422
423 $to2 = getEmails(Env::v('to_contacts'));
424 $cc2 = getEmails(Env::v('cc_contacts'));
425 $txt = str_replace('^M', '', Env::v('contenu'));
3c7b9bad
SJ
426 $to = str_replace(';', ',', Env::t('to'));
427 $subj = Env::t('sujet');
428 $from = Env::t('from');
429 $cc = str_replace(';', ',', Env::t('cc'));
430 $bcc = str_replace(';', ',', Env::t('bcc'));
5e68682e 431
6ff4f8c0
SJ
432 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
433 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
434 $email = trim($email);
435 if ($email != '' && !preg_match($email_regex, $email)) {
436 $page->trigError("L'adresse email " . $email . ' est erronée.');
437 $error = true;
438 }
439 }
5e68682e 440 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 441 $page->trigError("Indique au moins un destinataire.");
6ff4f8c0
SJ
442 $error = true;
443 }
444
445 if ($error) {
f3df6d38 446 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
447 } else {
448 $mymail = new PlMailer();
449 $mymail->setFrom($from);
450 $mymail->setSubject($subj);
451 if (!empty($to)) { $mymail->addTo($to); }
452 if (!empty($cc)) { $mymail->addCc($cc); }
453 if (!empty($bcc)) { $mymail->addBcc($bcc); }
454 if (!empty($to2)) { $mymail->addTo($to2); }
455 if (!empty($cc2)) { $mymail->addCc($cc2); }
f3df6d38 456 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
457 foreach ($files as $name=>&$upload) {
458 $mymail->addUploadAttachment($upload, $name);
459 }
460 if (Env::v('nowiki')) {
461 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
462 } else {
463 $mymail->setWikiBody($txt);
464 }
465 if ($mymail->send()) {
faefdbb7 466 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 467 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 468 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 469 } else {
a7d35093 470 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 471 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 472 }
81b5b746 473 }
474 }
475 } else {
3360c04f
FB
476 $res = XDB::query("SELECT data
477 FROM email_send_save
478 WHERE uid = {?}", S::i('uid'));
479 if ($res->numRows() == 0) {
f3df6d38 480 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 481 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
482 } else {
483 $data = unserialize($res->fetchOneCell());
484 $_REQUEST = array_merge($_REQUEST, $data);
485 }
81b5b746 486 }
487
2d5264c6
FB
488 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
489 new UFC_Registered()),
490 UserFilter::sortByName());
491 $contacts = $uf->getProfiles();
48e683dd 492 $page->assign('contacts', $contacts);
5e68682e 493 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 494 $page->assign('user', S::user());
81b5b746 495 }
496
26ba053e 497 function handler_test($page, $hruid = null)
5ff3f06b 498 {
e4ecada4
VZ
499 require_once 'emails.inc.php';
500
46504fb3
VZ
501 if (!S::has_xsrf_token()) {
502 return PL_FORBIDDEN;
503 }
d0c3e04d
VZ
504
505 // Retrieves the User object for the test email recipient.
dd70cd28 506 if (S::admin() && $hruid) {
d0c3e04d
VZ
507 $user = User::getSilent($hruid);
508 } else {
509 $user = S::user();
510 }
511 if (!$user) {
512 return PL_NOT_FOUND;
5ff3f06b 513 }
e4ecada4 514
d0c3e04d 515 // Sends the test email.
12a587df 516 $redirect = new Redirect($user);
e4ecada4
VZ
517
518 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 519 $mailer->assign('email', $user->bestEmail());
e4ecada4 520 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
521 $mailer->assign('display_name', $user->displayName());
522 $mailer->assign('sexe', $user->isFemale());
523 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
524 exit;
525 }
526
26ba053e 527 function handler_rewrite_in($page, $mail, $hash)
3d17e48f
FB
528 {
529 $page->changeTpl('emails/rewrite.tpl');
530 $page->assign('option', 'in');
531 if (empty($mail) || empty($hash)) {
532 return PL_NOT_FOUND;
533 }
534 $pos = strrpos($mail, '_');
535 if ($pos === false) {
536 return PL_NOT_FOUND;
537 }
538 $mail{$pos} = '@';
b4503762
SJ
539 $res = XDB::query('SELECT COUNT(*)
540 FROM email_redirect_account
541 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
3d17e48f
FB
542 $mail, $hash);
543 $count = intval($res->fetchOneCell());
544 if ($count > 0) {
b4503762 545 XDB::query('UPDATE email_redirect_account
3d17e48f 546 SET allow_rewrite = true, hash = NULL
b4503762
SJ
547 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
548 $mail, $hash);
3d17e48f
FB
549 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
550 return;
551 }
552 return PL_NOT_FOUND;
553 }
554
26ba053e 555 function handler_rewrite_out($page, $mail, $hash)
3d17e48f
FB
556 {
557 $page->changeTpl('emails/rewrite.tpl');
558 $page->assign('option', 'out');
559 if (empty($mail) || empty($hash)) {
560 return PL_NOT_FOUND;
561 }
562 $pos = strrpos($mail, '_');
563 if ($pos === false) {
564 return PL_NOT_FOUND;
565 }
566 $mail{$pos} = '@';
b4503762
SJ
567 $res = XDB::query('SELECT COUNT(*)
568 FROM email_redirect_account
569 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
3d17e48f
FB
570 $mail, $hash);
571 $count = intval($res->fetchOneCell());
572 if ($count > 0) {
573 global $globals;
b4503762
SJ
574 $res = XDB::query('SELECT e.redirect, e.rewrite, a.hruid
575 FROM email_redirect_account AS e
576 INNER JOIN accounts AS a ON (e.uid = a.uid)
577 WHERE e.redirect = {?} AND e.hash = {?}',
3d17e48f 578 $mail, $hash);
b4503762 579 XDB::query('UPDATE email_redirect_account
3d17e48f 580 SET allow_rewrite = false, hash = NULL
b4503762
SJ
581 WHERE redirect = {?} AND hash = {?}',
582 $mail, $hash);
583 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
3d17e48f
FB
584 $mail = new PlMailer();
585 $mail->setFrom("webmaster@" . $globals->mail->domain);
586 $mail->addTo("support@" . $globals->mail->domain);
587 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
b4503762 588 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
3d17e48f
FB
589 $mail->send();
590 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
591 return;
592 }
593 return PL_NOT_FOUND;
594 }
595
26ba053e 596 function handler_imap_in($page, $hash = null, $login = null)
2ee43273
FB
597 {
598 $page->changeTpl('emails/imap_register.tpl');
12a587df 599 $user = null;
2ee43273 600 if (!empty($hash) || !empty($login)) {
12a587df
VZ
601 $user = User::getSilent($login);
602 if ($user) {
1bf36cd1
SJ
603 $req = XDB::query('SELECT 1
604 FROM newsletter_ins
605 WHERE uid = {?} AND hash = {?}',
606 $user->id(), $hash);
12a587df
VZ
607 if ($req->numRows() == 0) {
608 $user = null;
609 }
610 }
2ee43273
FB
611 }
612
b4503762 613 require_once 'emails.inc.php';
2ee43273 614 $page->assign('ok', false);
12a587df 615 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
b4503762 616 Email::activate_storage(S::user(), 'imap');
2ee43273 617 $page->assign('ok', true);
2ab3486b
SJ
618 $page->assign('yourself', S::user()->displayName());
619 $page->assign('sexe', S::user()->isFemale());
12a587df 620 } else if (!S::logged() && $user) {
b4503762 621 Email::activate_storage($user, 'imap');
2ee43273 622 $page->assign('ok', true);
2ab3486b 623 $page->assign('yourself', $user->displayName());
12a587df 624 $page->assign('sexe', $user->isFemale());
2ee43273
FB
625 }
626 }
627
26ba053e 628 function handler_broken($page, $warn = null, $email = null)
81b5b746 629 {
630 require_once 'emails.inc.php';
8f201b69
FB
631 $wp = new PlWikiPage('Xorg.PatteCassée');
632 $wp->buildCache();
81b5b746 633
634 global $globals;
635
636 $page->changeTpl('emails/broken.tpl');
637
40d428d8 638 if ($warn == 'warn' && $email) {
d4b25d1a 639 S::assert_xsrf_token();
40d428d8 640
a9fd3272 641 // Usual verifications.
81b5b746 642 $email = valide_email($email);
a9fd3272
SJ
643 $uid = XDB::fetchOneCell('SELECT uid
644 FROM email_redirect_account
645 WHERE redirect = {?}', $email);
646
2c93e70e
FB
647 if ($uid) {
648 $dest = User::getWithUID($uid);
649
650 $mail = new PlMailer('emails/broken-web.mail.tpl');
651 $mail->assign('email', $email);
652 $mail->assign('request', S::user());
653 $mail->sendTo($dest);
6bb2f79a 654 $page->trigSuccess('Email envoyé&nbsp;!');
81b5b746 655 }
40d428d8
VZ
656 } elseif (Post::has('email')) {
657 S::assert_xsrf_token();
658
a9fd3272 659 $email = Post::t('email');
81b5b746 660
f036c896 661 if (!User::isForeignEmailAddress($email)) {
81b5b746 662 $page->assign('neuneu', true);
663 } else {
a9fd3272
SJ
664 $user = mark_broken_email($email);
665 $page->assign('user', $user);
666 $page->assign('email', $email);
81b5b746 667 }
668 }
669 }
9e570fe0 670
26ba053e 671 function handler_duplicated($page, $action = 'list', $email = null)
9e570fe0 672 {
673 $page->changeTpl('emails/duplicated.tpl');
674
675 $states = array('pending' => 'En attente...',
a7de4ef7 676 'safe' => 'Pas d\'inquiétude',
9e570fe0 677 'unsafe' => 'Recherches en cours',
678 'dangerous' => 'Usurpations par cette adresse');
679 $page->assign('states', $states);
680
40d428d8
VZ
681 if (Post::has('action')) {
682 S::assert_xsrf_token();
46504fb3 683 }
9e570fe0 684 switch (Post::v('action')) {
46504fb3 685 case 'create':
9e570fe0 686 if (trim(Post::v('emailN')) != '') {
06f4daf9 687 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
9e570fe0 688 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
689 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
690 };
691 break;
692
46504fb3 693 case 'edit':
06f4daf9 694 Xdb::execute('UPDATE email_watch
9e570fe0 695 SET state = {?}, last = NOW(), uid = {?}, description = {?}
696 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
697 break;
698
46504fb3 699 default:
9e570fe0 700 if ($action == 'delete' && !is_null($email)) {
06f4daf9 701 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
9e570fe0 702 }
703 }
704 if ($action != 'create' && $action != 'edit') {
705 $action = 'list';
706 }
707 $page->assign('action', $action);
708
709 if ($action == 'list') {
34b566f4
SJ
710 $it = XDB::iterRow('SELECT w.email, w.detection, w.state, s.email AS forlife
711 FROM email_watch AS w
712 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
713 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
714 ORDER BY w.state, w.email, s.email');
9e570fe0 715
716 $table = array();
717 $props = array();
718 while (list($email, $date, $state, $forlife) = $it->next()) {
719 if (count($props) == 0 || $props['mail'] != $email) {
720 if (count($props) > 0) {
721 $table[] = $props;
722 }
723 $props = array('mail' => $email,
724 'detection' => $date,
725 'state' => $state,
726 'users' => array($forlife));
727 } else {
728 $props['users'][] = $forlife;
729 }
730 }
731 if (count($props) > 0) {
732 $table[] = $props;
733 }
734 $page->assign('table', $table);
735 } elseif ($action == 'edit') {
34b566f4
SJ
736 $it = XDB::iterRow('SELECT w.detection, w.state, w.last, w.description,
737 a.hruid AS edit, s.email AS forlife
738 FROM email_watch AS w
739 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
740 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
741 INNER JOIN accounts AS a ON (w.uid = a.uid)
742 WHERE w.email = {?}
743 ORDER BY s.email',
744 $email);
9e570fe0 745
746 $props = array();
747 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
748 if (count($props) == 0) {
749 $props = array('mail' => $email,
750 'detection' => $detection,
751 'state' => $state,
752 'last' => $last,
753 'description' => $description,
754 'edit' => $edit,
755 'users' => array($forlife));
756 } else {
757 $props['users'][] = $forlife;
758 }
759 }
760 $page->assign('doublon', $props);
761 }
762 }
d4b25d1a 763
26ba053e 764 function handler_lost($page, $action = 'list', $email = null)
7727ffc7 765 {
766 $page->changeTpl('emails/lost.tpl');
eaf30d86 767
d4b25d1a 768 $page->assign('lost_emails',
73682f22 769 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
34b566f4
SJ
770 FROM accounts AS a
771 INNER JOIN account_types AS at ON (a.type = at.type)
772 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
773 AND er.type != \'imap\' AND er.type != \'homonym\')
774 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
775 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
776 WHERE a.state = \'active\' AND er.redirect IS NULL AND FIND_IN_SET(\'mail\', at.perms)
777 GROUP BY a.uid
73682f22 778 ORDER BY pd.promo, a.hruid'));
7727ffc7 779 }
67e06366 780
26ba053e 781 function handler_broken_addr($page)
67e06366
SJ
782 {
783 require_once 'emails.inc.php';
784 $page->changeTpl('emails/broken_addr.tpl');
785
786 if (Env::has('sort_broken')) {
787 S::assert_xsrf_token();
788
789 $list = trim(Env::v('list'));
790 if ($list == '') {
791 $page->trigError('La liste est vide.');
792 } else {
793 $valid_emails = array();
794 $invalid_emails = array();
795 $broken_list = explode("\n", $list);
796 sort($broken_list);
797 foreach ($broken_list as $orig_email) {
35a22488
SJ
798 $orig_email = trim($orig_email);
799 if ($orig_email != '') {
800 $email = valide_email($orig_email);
801 if (empty($email) || $email == '@') {
802 $invalid_emails[] = trim($orig_email) . ': invalid email';
803 } elseif (!in_array($email, $valid_emails)) {
a9fd3272
SJ
804 $nb = XDB::fetchOneCell('SELECT COUNT(*)
805 FROM email_redirect_account
806 WHERE redirect = {?}', $email);
807 if ($nb > 0) {
35a22488
SJ
808 $valid_emails[] = $email;
809 } else {
a9fd3272 810 $invalid_emails[] = $orig_email . ': no such redirection';
35a22488 811 }
67e06366
SJ
812 }
813 }
814 }
815
816 $page->assign('valid_emails', $valid_emails);
817 $page->assign('invalid_emails', $invalid_emails);
818 }
819 }
820
821 if (Env::has('process_broken')) {
822 S::assert_xsrf_token();
823
824 $list = trim(Env::v('list'));
825 if ($list == '') {
826 $page->trigError('La liste est vide.');
827 } else {
67e06366
SJ
828 $broken_user_list = array();
829 $broken_list = explode("\n", $list);
830 sort($broken_list);
67e06366 831
a9fd3272
SJ
832 foreach ($broken_list as $email) {
833 if ($user = mark_broken_email($email, true)) {
834 if ($user['nb_mails'] > 0) {
67e06366 835 $mail = new PlMailer('emails/broken.mail.tpl');
f036c896 836 $mail->addTo($user);
a9fd3272 837 $mail->assign('user', $user);
67e06366
SJ
838 $mail->assign('email', $email);
839 $mail->send();
840 }
841
a9fd3272
SJ
842 if (!isset($broken_user_list[$user['alias']])) {
843 $broken_user_list[$user['alias']] = array($email);
67e06366 844 } else {
a9fd3272 845 $broken_user_list[$user['alias']][] = $email;
67e06366
SJ
846 }
847 }
848 }
849
a9fd3272
SJ
850 XDB::execute('UPDATE email_redirect_account
851 SET broken_level = broken_level - 1
852 WHERE flags = \'active\' AND broken_level > 1
853 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()');
854 XDB::execute('UPDATE email_redirect_account
855 SET broken_level = 0
856 WHERE flags = \'active\' AND broken_level = 1
857 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()');
67e06366
SJ
858
859 // Output the list of users with recently broken addresses,
860 // along with the count of valid redirections.
35a22488 861 require_once 'notifs.inc.php';
023c46fb 862 pl_cached_content_headers('text/x-csv', 1);
67e06366
SJ
863
864 $csv = fopen('php://output', 'w');
7b58e5e4 865 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
67e06366
SJ
866 foreach ($broken_user_list as $alias => $mails) {
867 $sel = Xdb::query(
a9fd3272
SJ
868 'SELECT a.uid, count(DISTINCT(r.redirect)) AS nb_mails,
869 IFNULL(pd.public_name, a.full_name) AS fullname,
870 IFNULL(pd.promo, 0) AS promo, IFNULL(pce.name, \'Aucun\') AS corps,
871 IFNULL(pje.name, \'Aucun\') AS job, GROUP_CONCAT(pn.address SEPARATOR \', \') AS networking
872 FROM email_source_account AS s
873 INNER JOIN accounts AS a ON (s.uid = a.uid)
874 LEFT JOIN email_redirect_account AS r ON (a.uid = r.uid AND r.broken_level = 0 AND r.flags = \'active\' AND
875 (r.type = \'smtp\' OR r.type = \'googleapps\'))
876 LEFT JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
877 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
878 LEFT JOIN profile_corps AS pc ON (pc.pid = ap.pid)
879 LEFT JOIN profile_corps_enum AS pce ON (pc.current_corpsid = pce.id)
880 LEFT JOIN profile_job AS pj ON (pj.pid = ap.pid)
881 LEFT JOIN profile_job_enum AS pje ON (pj.jobid = pje.id)
882 LEFT JOIN profile_networking AS pn ON (pn.pid = ap.pid)
883 WHERE s.email = {?}
884 GROUP BY a.uid', $alias);
67e06366
SJ
885
886 if ($x = $sel->fetchOneAssoc()) {
ae6cd633 887 if ($x['nb_mails'] == 0) {
e03a98e9
SJ
888 $user = User::getSilentWithUID($x['uid']);
889 $profile = $user->profile();
890 WatchProfileUpdate::register($profile, 'broken');
ae6cd633 891 }
a06602ae 892 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
6139d6cb 893 join(',', $mails), $x['nb_mails'],
7b58e5e4
SJ
894 'https://www.polytechnique.org/marketing/broken/' . $alias,
895 $x['corps'], $x['job'], $x['networking']), ';');
67e06366
SJ
896 }
897 }
898 fclose($csv);
899 exit;
900 }
901 }
902 }
81b5b746 903}
904
a7de4ef7 905// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 906?>