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