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