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