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