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