Add UFC_Hrpid.
[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 }
396 $rel = Env::v('contacts');
397 $ret = array();
398 foreach ($aliases as $alias) {
399 $ret[$alias] = $rel[$alias];
400 }
401 return join(', ', $ret);
402 }
403
5e68682e 404 $error = false;
da419622 405 foreach ($_FILES as &$file) {
f3df6d38 406 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 407 $page->trigError(PlUpload::$lastError);
5e68682e
FB
408 $error = true;
409 break;
da419622 410 }
411 }
412
5e68682e
FB
413 if (!$error) {
414 XDB::execute("DELETE FROM email_send_save
48e683dd
FB
415 WHERE uid = {?}",
416 S::user()->id());
5e68682e
FB
417
418 $to2 = getEmails(Env::v('to_contacts'));
419 $cc2 = getEmails(Env::v('cc_contacts'));
420 $txt = str_replace('^M', '', Env::v('contenu'));
3c7b9bad
SJ
421 $to = str_replace(';', ',', Env::t('to'));
422 $subj = Env::t('sujet');
423 $from = Env::t('from');
424 $cc = str_replace(';', ',', Env::t('cc'));
425 $bcc = str_replace(';', ',', Env::t('bcc'));
5e68682e 426
6ff4f8c0
SJ
427 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
428 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
429 $email = trim($email);
430 if ($email != '' && !preg_match($email_regex, $email)) {
431 $page->trigError("L'adresse email " . $email . ' est erronée.');
432 $error = true;
433 }
434 }
5e68682e 435 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 436 $page->trigError("Indique au moins un destinataire.");
6ff4f8c0
SJ
437 $error = true;
438 }
439
440 if ($error) {
f3df6d38 441 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
442 } else {
443 $mymail = new PlMailer();
444 $mymail->setFrom($from);
445 $mymail->setSubject($subj);
446 if (!empty($to)) { $mymail->addTo($to); }
447 if (!empty($cc)) { $mymail->addCc($cc); }
448 if (!empty($bcc)) { $mymail->addBcc($bcc); }
449 if (!empty($to2)) { $mymail->addTo($to2); }
450 if (!empty($cc2)) { $mymail->addCc($cc2); }
f3df6d38 451 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
452 foreach ($files as $name=>&$upload) {
453 $mymail->addUploadAttachment($upload, $name);
454 }
455 if (Env::v('nowiki')) {
456 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
457 } else {
458 $mymail->setWikiBody($txt);
459 }
460 if ($mymail->send()) {
faefdbb7 461 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 462 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 463 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 464 } else {
a7d35093 465 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 466 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 467 }
81b5b746 468 }
469 }
470 } else {
3360c04f
FB
471 $res = XDB::query("SELECT data
472 FROM email_send_save
473 WHERE uid = {?}", S::i('uid'));
474 if ($res->numRows() == 0) {
f3df6d38 475 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 476 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
477 } else {
478 $data = unserialize($res->fetchOneCell());
479 $_REQUEST = array_merge($_REQUEST, $data);
480 }
81b5b746 481 }
482
48e683dd
FB
483 $contacts = S::user()->getContacts();
484 $page->assign('contacts', $contacts);
5e68682e 485 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 486 $page->assign('user', S::user());
81b5b746 487 }
488
d0c3e04d 489 function handler_test(&$page, $hruid = null)
5ff3f06b 490 {
e4ecada4
VZ
491 require_once 'emails.inc.php';
492
46504fb3
VZ
493 if (!S::has_xsrf_token()) {
494 return PL_FORBIDDEN;
495 }
d0c3e04d
VZ
496
497 // Retrieves the User object for the test email recipient.
dd70cd28 498 if (S::admin() && $hruid) {
d0c3e04d
VZ
499 $user = User::getSilent($hruid);
500 } else {
501 $user = S::user();
502 }
503 if (!$user) {
504 return PL_NOT_FOUND;
5ff3f06b 505 }
e4ecada4 506
d0c3e04d 507 // Sends the test email.
12a587df 508 $redirect = new Redirect($user);
e4ecada4
VZ
509
510 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 511 $mailer->assign('email', $user->bestEmail());
e4ecada4 512 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
513 $mailer->assign('display_name', $user->displayName());
514 $mailer->assign('sexe', $user->isFemale());
515 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
516 exit;
517 }
518
3d17e48f
FB
519 function handler_rewrite_in(&$page, $mail, $hash)
520 {
521 $page->changeTpl('emails/rewrite.tpl');
522 $page->assign('option', 'in');
523 if (empty($mail) || empty($hash)) {
524 return PL_NOT_FOUND;
525 }
526 $pos = strrpos($mail, '_');
527 if ($pos === false) {
528 return PL_NOT_FOUND;
529 }
530 $mail{$pos} = '@';
531 $res = XDB::query("SELECT COUNT(*)
532 FROM emails
533 WHERE email = {?} AND hash = {?}",
534 $mail, $hash);
535 $count = intval($res->fetchOneCell());
536 if ($count > 0) {
537 XDB::query("UPDATE emails
538 SET allow_rewrite = true, hash = NULL
539 WHERE email = {?} AND hash = {?}",
540 $mail, $hash);
541 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
542 return;
543 }
544 return PL_NOT_FOUND;
545 }
546
547 function handler_rewrite_out(&$page, $mail, $hash)
548 {
549 $page->changeTpl('emails/rewrite.tpl');
550 $page->assign('option', 'out');
551 if (empty($mail) || empty($hash)) {
552 return PL_NOT_FOUND;
553 }
554 $pos = strrpos($mail, '_');
555 if ($pos === false) {
556 return PL_NOT_FOUND;
557 }
558 $mail{$pos} = '@';
559 $res = XDB::query("SELECT COUNT(*)
560 FROM emails
561 WHERE email = {?} AND hash = {?}",
562 $mail, $hash);
563 $count = intval($res->fetchOneCell());
564 if ($count > 0) {
565 global $globals;
566 $res = XDB::query("SELECT e.email, e.rewrite, a.alias
567 FROM emails AS e
fe13bc1d 568 INNER JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
3d17e48f
FB
569 WHERE e.email = {?} AND e.hash = {?}",
570 $mail, $hash);
571 XDB::query("UPDATE emails
572 SET allow_rewrite = false, hash = NULL
573 WHERE email = {?} AND hash = {?}",
574 $mail, $hash);
575 list($mail, $rewrite, $forlife) = $res->fetchOneRow();
576 $mail = new PlMailer();
577 $mail->setFrom("webmaster@" . $globals->mail->domain);
578 $mail->addTo("support@" . $globals->mail->domain);
579 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
580 $mail->setTxtBody("$forlife a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
581 $mail->send();
582 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
583 return;
584 }
585 return PL_NOT_FOUND;
586 }
587
2ee43273
FB
588 function handler_imap_in(&$page, $hash = null, $login = null)
589 {
590 $page->changeTpl('emails/imap_register.tpl');
12a587df 591 $user = null;
2ee43273 592 if (!empty($hash) || !empty($login)) {
12a587df
VZ
593 $user = User::getSilent($login);
594 if ($user) {
1bf36cd1
SJ
595 $req = XDB::query('SELECT 1
596 FROM newsletter_ins
597 WHERE uid = {?} AND hash = {?}',
598 $user->id(), $hash);
12a587df
VZ
599 if ($req->numRows() == 0) {
600 $user = null;
601 }
602 }
2ee43273
FB
603 }
604
605 require_once('emails.inc.php');
606 $page->assign('ok', false);
12a587df
VZ
607 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
608 $storage = new EmailStorage(S::user(), 'imap');
2ee43273
FB
609 $storage->activate();
610 $page->assign('ok', true);
611 $page->assign('prenom', S::v('prenom'));
e2cea47d 612 $page->assign('sexe', S::v('femme'));
12a587df
VZ
613 } else if (!S::logged() && $user) {
614 $storage = new EmailStorage($user, 'imap');
2ee43273
FB
615 $storage->activate();
616 $page->assign('ok', true);
12a587df
VZ
617 $page->assign('prenom', $user->displayName());
618 $page->assign('sexe', $user->isFemale());
2ee43273
FB
619 }
620 }
621
81b5b746 622 function handler_broken(&$page, $warn = null, $email = null)
623 {
624 require_once 'emails.inc.php';
8f201b69
FB
625 $wp = new PlWikiPage('Xorg.PatteCassée');
626 $wp->buildCache();
81b5b746 627
628 global $globals;
629
630 $page->changeTpl('emails/broken.tpl');
631
40d428d8 632 if ($warn == 'warn' && $email) {
d4b25d1a 633 S::assert_xsrf_token();
40d428d8 634
81b5b746 635 $email = valide_email($email);
a7de4ef7 636 // vérifications d'usage
2c93e70e
FB
637 $uid = XDB::fetchOneCell("SELECT uid
638 FROM emails
639 WHERE email = {?}", $email);
640 if ($uid) {
641 $dest = User::getWithUID($uid);
642
643 $mail = new PlMailer('emails/broken-web.mail.tpl');
644 $mail->assign('email', $email);
645 $mail->assign('request', S::user());
646 $mail->sendTo($dest);
6bb2f79a 647 $page->trigSuccess('Email envoyé&nbsp;!');
81b5b746 648 }
40d428d8
VZ
649 } elseif (Post::has('email')) {
650 S::assert_xsrf_token();
651
5e2307dc 652 $email = valide_email(Post::v('email'));
81b5b746 653
654 list(,$fqdn) = explode('@', $email);
655 $fqdn = strtolower($fqdn);
40d428d8 656 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
81b5b746 657 $page->assign('neuneu', true);
658 } else {
659 $page->assign('email',$email);
2c93e70e
FB
660 $x = XDB::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne,
661 (count(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
662 FROM emails as e1
663 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
664 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
81b5b746 665 AND FIND_IN_SET('active', e2.flags)
666 AND e1.email != e2.email)
2c93e70e
FB
667 WHERE e1.email = {?}
668 GROUP BY e1.uid", $email);
669 if ($x) {
a7de4ef7 670 // on écrit dans la base que l'adresse est cassée
81b5b746 671 if (!$x['panne']) {
2c93e70e
FB
672 XDB::execute("UPDATE emails
673 SET panne=NOW(), last=NOW(), panne_level = 1
674 WHERE email = {?}", $email);
74938c82 675 } else {
2c93e70e
FB
676 XDB::execute("UPDATE emails
677 SET panne_level = 1
678 WHERE email = {?} AND panne_level = 0", $email);
81b5b746 679 }
2c93e70e 680 $x['user'] = User::getWithUID($x['uid']);
81b5b746 681 $page->assign_by_ref('x', $x);
682 }
683 }
684 }
685 }
9e570fe0 686
687 function handler_duplicated(&$page, $action = 'list', $email = null)
688 {
689 $page->changeTpl('emails/duplicated.tpl');
690
691 $states = array('pending' => 'En attente...',
a7de4ef7 692 'safe' => 'Pas d\'inquiétude',
9e570fe0 693 'unsafe' => 'Recherches en cours',
694 'dangerous' => 'Usurpations par cette adresse');
695 $page->assign('states', $states);
696
40d428d8
VZ
697 if (Post::has('action')) {
698 S::assert_xsrf_token();
46504fb3 699 }
9e570fe0 700 switch (Post::v('action')) {
46504fb3 701 case 'create':
9e570fe0 702 if (trim(Post::v('emailN')) != '') {
06f4daf9 703 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
9e570fe0 704 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
705 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
706 };
707 break;
708
46504fb3 709 case 'edit':
06f4daf9 710 Xdb::execute('UPDATE email_watch
9e570fe0 711 SET state = {?}, last = NOW(), uid = {?}, description = {?}
712 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
713 break;
714
46504fb3 715 default:
9e570fe0 716 if ($action == 'delete' && !is_null($email)) {
06f4daf9 717 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
9e570fe0 718 }
719 }
720 if ($action != 'create' && $action != 'edit') {
721 $action = 'list';
722 }
723 $page->assign('action', $action);
724
725 if ($action == 'list') {
726 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
06f4daf9 727 FROM email_watch AS w
ca6d07f4 728 LEFT JOIN emails AS e USING(email)
fe13bc1d 729 LEFT JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
9e570fe0 730 ORDER BY w.state, w.email, a.alias";
731 $it = Xdb::iterRow($sql);
732
733 $table = array();
734 $props = array();
735 while (list($email, $date, $state, $forlife) = $it->next()) {
736 if (count($props) == 0 || $props['mail'] != $email) {
737 if (count($props) > 0) {
738 $table[] = $props;
739 }
740 $props = array('mail' => $email,
741 'detection' => $date,
742 'state' => $state,
743 'users' => array($forlife));
744 } else {
745 $props['users'][] = $forlife;
746 }
747 }
748 if (count($props) > 0) {
749 $table[] = $props;
750 }
751 $page->assign('table', $table);
752 } elseif ($action == 'edit') {
753 $sql = "SELECT w.detection, w.state, w.last, w.description,
754 a1.alias AS edit, a2.alias AS forlife
06f4daf9 755 FROM email_watch AS w
fe13bc1d 756 LEFT JOIN aliases AS a1 ON (a1.uid = w.uid AND a1.type = 'a_vie')
9615c895 757 LEFT JOIN emails AS e ON (w.email = e.email)
fe13bc1d 758 LEFT JOIN aliases AS a2 ON (a2.uid = e.uid AND a2.type = 'a_vie')
9e570fe0 759 WHERE w.email = {?}
760 ORDER BY a2.alias";
761 $it = Xdb::iterRow($sql, $email);
762
763 $props = array();
764 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
765 if (count($props) == 0) {
766 $props = array('mail' => $email,
767 'detection' => $detection,
768 'state' => $state,
769 'last' => $last,
770 'description' => $description,
771 'edit' => $edit,
772 'users' => array($forlife));
773 } else {
774 $props['users'][] = $forlife;
775 }
776 }
777 $page->assign('doublon', $props);
778 }
779 }
d4b25d1a 780
7727ffc7 781 function handler_lost(&$page, $action = 'list', $email = null)
782 {
783 $page->changeTpl('emails/lost.tpl');
eaf30d86 784
d4b25d1a
FB
785 // TODO: Order by promo.
786 $page->assign('lost_emails',
787 XDB::iterator("SELECT a.uid, a.hruid
788 FROM accounts AS a
789 INNER JOIN email_options AS eo ON (eo.uid = a.uid)
790 LEFT JOIN emails AS e ON (a.uid = e.uid AND FIND_IN_SET('active', e.flags))
791 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', eo.storage) = 0 AND
792 a.state = 'active'
793 ORDER BY a.hruid"));
7727ffc7 794 }
67e06366
SJ
795
796 function handler_broken_addr(&$page)
797 {
798 require_once 'emails.inc.php';
799 $page->changeTpl('emails/broken_addr.tpl');
800
801 if (Env::has('sort_broken')) {
802 S::assert_xsrf_token();
803
804 $list = trim(Env::v('list'));
805 if ($list == '') {
806 $page->trigError('La liste est vide.');
807 } else {
808 $valid_emails = array();
809 $invalid_emails = array();
810 $broken_list = explode("\n", $list);
811 sort($broken_list);
812 foreach ($broken_list as $orig_email) {
35a22488
SJ
813 $orig_email = trim($orig_email);
814 if ($orig_email != '') {
815 $email = valide_email($orig_email);
816 if (empty($email) || $email == '@') {
817 $invalid_emails[] = trim($orig_email) . ': invalid email';
818 } elseif (!in_array($email, $valid_emails)) {
819 $res = XDB::query('SELECT COUNT(*)
820 FROM emails
821 WHERE email = {?}', $email);
822 if ($res->fetchOneCell() > 0) {
823 $valid_emails[] = $email;
824 } else {
825 $invalid_emails[] = "$orig_email: no such redirection";
826 }
67e06366
SJ
827 }
828 }
829 }
830
831 $page->assign('valid_emails', $valid_emails);
832 $page->assign('invalid_emails', $invalid_emails);
833 }
834 }
835
836 if (Env::has('process_broken')) {
837 S::assert_xsrf_token();
838
839 $list = trim(Env::v('list'));
840 if ($list == '') {
841 $page->trigError('La liste est vide.');
842 } else {
843 global $platal;
844
845 $broken_user_list = array();
846 $broken_list = explode("\n", $list);
847 sort($broken_list);
848 foreach ($broken_list as $orig_email) {
849 $email = valide_email(trim($orig_email));
850 if (empty($email) || $email == '@') {
851 continue;
852 }
853
854 $sel = XDB::query(
855 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
a06602ae 856 acc.full_name, a.alias
67e06366
SJ
857 FROM emails AS e1
858 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
859 AND e1.email != e2.email)
a06602ae 860 INNER JOIN accounts AS acc ON (e1.uid = acc.uid)
fe13bc1d 861 INNER JOIN aliases AS a ON (acc.uid = a.uid AND FIND_IN_SET('bestalias', a.flags))
67e06366
SJ
862 WHERE e1.email = {?}
863 GROUP BY e1.uid", $email);
864
865 if ($x = $sel->fetchOneAssoc()) {
866 if (!$x['panne']) {
867 XDB::execute('UPDATE emails
868 SET panne=NOW(), last=NOW(), panne_level = 1
869 WHERE email = {?}',
870 $email);
871 } else {
872 XDB::execute('UPDATE emails
873 SET last = CURDATE(), panne_level = panne_level + 1
874 WHERE email = {?}
875 AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
876 $email);
877 }
878
879 if (!empty($x['nb_mails'])) {
880 $mail = new PlMailer('emails/broken.mail.tpl');
a06602ae 881 $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
67e06366
SJ
882 . $globals->mail->domain . '>');
883 $mail->assign('x', $x);
884 $mail->assign('email', $email);
885 $mail->send();
886 }
887
888 if (!isset($broken_user_list[$x['alias']])) {
889 $broken_user_list[$x['alias']] = array($email);
890 } else {
891 $broken_user_list[$x['alias']][] = $email;
892 }
893 }
894 }
895
896 XDB::execute("UPDATE emails
897 SET panne_level = panne_level - 1
898 WHERE flags = 'active' AND panne_level > 1
899 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
900 XDB::execute("UPDATE emails
901 SET panne_level = 0
902 WHERE flags = 'active' AND panne_level = 1
903 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
904
905 // Output the list of users with recently broken addresses,
906 // along with the count of valid redirections.
35a22488 907 require_once 'notifs.inc.php';
3cb500d5 908 pl_content_headers("text/x-csv");
67e06366
SJ
909
910 $csv = fopen('php://output', 'w');
a06602ae 911 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url'), ';');
67e06366
SJ
912 foreach ($broken_user_list as $alias => $mails) {
913 $sel = Xdb::query(
a06602ae
RB
914 "SELECT acc.uid, count(e.email) AS nb_mails,
915 IFNULL(pd.public_name, acc.full_name) AS fullname,
916 IFNULL(pd.promo, 0) AS promo,
917 FROM aliases AS a
918 INNER JOIN accounts AS acc ON a.id = acc.uid
919 LEFT JOIN emails AS e ON (e.uid = acc.uid
67e06366 920 AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
a06602ae
RB
921 LEFT JOIN account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
922 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
67e06366 923 WHERE a.alias = {?}
a06602ae 924 GROUP BY acc.uid", $alias);
67e06366
SJ
925
926 if ($x = $sel->fetchOneAssoc()) {
ae6cd633 927 if ($x['nb_mails'] == 0) {
1bf36cd1 928 register_profile_update($x['uid'], 'broken');
ae6cd633 929 }
a06602ae 930 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
6139d6cb
SJ
931 join(',', $mails), $x['nb_mails'],
932 'https://www.polytechnique.org/marketing/broken/' . $alias), ';');
67e06366
SJ
933 }
934 }
935 fclose($csv);
936 exit;
937 }
938 }
939 }
81b5b746 940}
941
a7de4ef7 942// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 943?>