Take into account alias visibility setting. (Closes #1136)
[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 exit;
202 }
203
204 $page->assign('actuel', $alias);
205 $page->assign('user', $user);
206 $page->assign('mail_public', $visibility);
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
217 $user = S::user();
218 $page->assign_by_ref('user', $user);
219 $page->assign('eleve', $user->promo() >= date("Y") - 5);
220
221 $redirect = new Redirect($user);
222
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
228 // Apply email redirection change requests.
229 $result = SUCCESS;
230 if ($action == 'remove' && $email) {
231 $result = $redirect->delete_email($email);
232 }
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
247 if (Env::has('emailop')) {
248 S::assert_xsrf_token();
249
250 $actifs = Env::v('emails_actifs', Array());
251 print_r(Env::v('emails_rewrite'));
252 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
253 $error_email = false;
254 $new_email = Env::v('email');
255 if ($new_email == "new@example.org") {
256 $new_email = Env::v('email_new');
257 }
258 $result = $redirect->add_email($new_email);
259 if ($result == ERROR_INVALID_EMAIL) {
260 $error_email = true;
261 $page->assign('email', $new_email);
262 }
263 $page->assign('retour', $result);
264 $page->assign('error_email', $error_email);
265 } elseif (empty($actifs)) {
266 $result = ERROR_INACTIVE_REDIRECTION;
267 } elseif (is_array($actifs)) {
268 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
269 }
270 }
271
272 switch ($result) {
273 case ERROR_INACTIVE_REDIRECTION:
274 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
275 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
276 break;
277 case ERROR_INVALID_EMAIL:
278 $page->trigError('Erreur : l\'email n\'est pas valide.');
279 break;
280 case ERROR_LOOP_EMAIL:
281 $page->trigError('Erreur : ' . $user->forlifeEmail()
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
287 // Fetch the @alias_dom email alias, if any.
288 $res = XDB::query(
289 "SELECT alias
290 FROM virtual
291 INNER JOIN virtual_redirect USING(vid)
292 WHERE (redirect={?} OR redirect={?})
293 AND alias LIKE '%@{$globals->mail->alias_dom}'",
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);
298 $melix = $res->fetchOneCell();
299 if ($melix) {
300 list($melix) = explode('@', $melix);
301 $page->assign('melix',$melix);
302 }
303
304 // Fetch existing email aliases.
305 $res = XDB::query(
306 "SELECT alias,expire
307 FROM aliases
308 WHERE uid={?} AND (type='a_vie' OR type='alias')
309 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
310 $page->assign('alias', $res->fetchAllAssoc());
311 $page->assign('emails', $redirect->emails);
312
313 // Display GoogleApps acount information.
314 require_once 'googleapps.inc.php';
315 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
316
317 require_once 'emails.combobox.inc.php';
318 fill_email_combobox($page);
319 }
320
321 function handler_antispam(&$page, $statut_filtre = null)
322 {
323 require_once 'emails.inc.php';
324 $wp = new PlWikiPage('Xorg.Antispam');
325 $wp->buildCache();
326
327 $page->changeTpl('emails/antispam.tpl');
328
329 $user = S::user();
330 $bogo = new Bogo($user);
331 if (isset($statut_filtre)) {
332 $bogo->change($statut_filtre + 0);
333 }
334 $page->assign('filtre', $bogo->level());
335 }
336
337 function handler_submit(&$page)
338 {
339 $wp = new PlWikiPage('Xorg.Mails');
340 $wp->buildCache();
341 $page->changeTpl('emails/submit_spam.tpl');
342
343 if (Post::has('send_email')) {
344 S::assert_xsrf_token();
345
346 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
347 if (!$upload) {
348 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
349 return;
350 }
351 $mime = $upload->contentType();
352 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
353 $upload->clear();
354 $page->trigError('Le fichier ne contient pas un email complet');
355 return;
356 }
357 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
358
359 global $globals;
360 $box = $type . '@' . $globals->mail->domain;
361 $mailer = new PlMailer();
362 $mailer->addTo($box);
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');
366 $mailer->send();
367 $page->trigSuccess('Le message a été transmis à ' . $box);
368 $upload->clear();
369 }
370 }
371
372 function handler_send(&$page)
373 {
374 $page->changeTpl('emails/send.tpl');
375 $page->addJsLink('ajax.js');
376
377 $page->setTitle('Envoyer un email');
378
379 // action si on recoit un formulaire
380 if (Post::has('save')) {
381 if (!S::has_xsrf_token()) {
382 return PL_FORBIDDEN;
383 }
384
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
391 VALUES ({?}, {?})",
392 S::user()->id('uid'), $data);
393 }
394 exit;
395 } else if (Env::v('submit') == 'Envoyer') {
396 S::assert_xsrf_token();
397
398 function getEmails($aliases)
399 {
400 if (!is_array($aliases)) {
401 return null;
402 }
403 $uf = new UserFilter(new UFC_Hrpid($aliases));
404 $users = $uf->iterUsers();
405 $ret = array();
406 while ($user = $users->next()) {
407 $ret[] = $user->forlife;
408 }
409 return join(', ', $ret);
410 }
411
412 $error = false;
413 foreach ($_FILES as &$file) {
414 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
415 $page->trigError(PlUpload::$lastError);
416 $error = true;
417 break;
418 }
419 }
420
421 if (!$error) {
422 XDB::execute("DELETE FROM email_send_save
423 WHERE uid = {?}",
424 S::user()->id());
425
426 $to2 = getEmails(Env::v('to_contacts'));
427 $cc2 = getEmails(Env::v('cc_contacts'));
428 $txt = str_replace('^M', '', Env::v('contenu'));
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'));
434
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 }
443 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
444 $page->trigError("Indique au moins un destinataire.");
445 $error = true;
446 }
447
448 if ($error) {
449 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
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); }
459 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
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()) {
469 $page->trigSuccess("Ton email a bien été envoyé.");
470 $_REQUEST = array('bcc' => S::user()->bestEmail());
471 PlUpload::clear(S::user()->login(), 'emails.send');
472 } else {
473 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
474 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
475 }
476 }
477 }
478 } else {
479 $res = XDB::query("SELECT data
480 FROM email_send_save
481 WHERE uid = {?}", S::i('uid'));
482 if ($res->numRows() == 0) {
483 PlUpload::clear(S::user()->login(), 'emails.send');
484 $_REQUEST['bcc'] = S::user()->bestEmail();
485 } else {
486 $data = unserialize($res->fetchOneCell());
487 $_REQUEST = array_merge($_REQUEST, $data);
488 }
489 }
490
491 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
492 new UFC_Registered()),
493 UserFilter::sortByName());
494 $contacts = $uf->getProfiles();
495 $page->assign('contacts', $contacts);
496 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
497 $page->assign('user', S::user());
498 }
499
500 function handler_test(&$page, $hruid = null)
501 {
502 require_once 'emails.inc.php';
503
504 if (!S::has_xsrf_token()) {
505 return PL_FORBIDDEN;
506 }
507
508 // Retrieves the User object for the test email recipient.
509 if (S::admin() && $hruid) {
510 $user = User::getSilent($hruid);
511 } else {
512 $user = S::user();
513 }
514 if (!$user) {
515 return PL_NOT_FOUND;
516 }
517
518 // Sends the test email.
519 $redirect = new Redirect($user);
520
521 $mailer = new PlMailer('emails/test.mail.tpl');
522 $mailer->assign('email', $user->bestEmail());
523 $mailer->assign('redirects', $redirect->active_emails());
524 $mailer->assign('display_name', $user->displayName());
525 $mailer->assign('sexe', $user->isFemale());
526 $mailer->send($user->isEmailFormatHtml());
527 exit;
528 }
529
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
579 INNER JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
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
599 function handler_imap_in(&$page, $hash = null, $login = null)
600 {
601 $page->changeTpl('emails/imap_register.tpl');
602 $user = null;
603 if (!empty($hash) || !empty($login)) {
604 $user = User::getSilent($login);
605 if ($user) {
606 $req = XDB::query('SELECT 1
607 FROM newsletter_ins
608 WHERE uid = {?} AND hash = {?}',
609 $user->id(), $hash);
610 if ($req->numRows() == 0) {
611 $user = null;
612 }
613 }
614 }
615
616 require_once('emails.inc.php');
617 $page->assign('ok', false);
618 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
619 $storage = new EmailStorage(S::user(), 'imap');
620 $storage->activate();
621 $page->assign('ok', true);
622 $page->assign('prenom', S::v('prenom'));
623 $page->assign('sexe', S::v('femme'));
624 } else if (!S::logged() && $user) {
625 $storage = new EmailStorage($user, 'imap');
626 $storage->activate();
627 $page->assign('ok', true);
628 $page->assign('prenom', $user->displayName());
629 $page->assign('sexe', $user->isFemale());
630 }
631 }
632
633 function handler_broken(&$page, $warn = null, $email = null)
634 {
635 require_once 'emails.inc.php';
636 $wp = new PlWikiPage('Xorg.PatteCassée');
637 $wp->buildCache();
638
639 global $globals;
640
641 $page->changeTpl('emails/broken.tpl');
642
643 if ($warn == 'warn' && $email) {
644 S::assert_xsrf_token();
645
646 $email = valide_email($email);
647 // vérifications d'usage
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);
658 $page->trigSuccess('Email envoyé&nbsp;!');
659 }
660 } elseif (Post::has('email')) {
661 S::assert_xsrf_token();
662
663 $email = valide_email(Post::v('email'));
664
665 list(,$fqdn) = explode('@', $email);
666 $fqdn = strtolower($fqdn);
667 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
668 $page->assign('neuneu', true);
669 } else {
670 $page->assign('email',$email);
671 $x = XDB::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne,
672 (count(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
673 FROM emails as e1
674 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
675 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
676 AND FIND_IN_SET('active', e2.flags)
677 AND e1.email != e2.email)
678 WHERE e1.email = {?}
679 GROUP BY e1.uid", $email);
680 if ($x) {
681 // on écrit dans la base que l'adresse est cassée
682 if (!$x['panne']) {
683 XDB::execute("UPDATE emails
684 SET panne=NOW(), last=NOW(), panne_level = 1
685 WHERE email = {?}", $email);
686 } else {
687 XDB::execute("UPDATE emails
688 SET panne_level = 1
689 WHERE email = {?} AND panne_level = 0", $email);
690 }
691 $x['user'] = User::getWithUID($x['uid']);
692 $page->assign_by_ref('x', $x);
693 }
694 }
695 }
696 }
697
698 function handler_duplicated(&$page, $action = 'list', $email = null)
699 {
700 $page->changeTpl('emails/duplicated.tpl');
701
702 $states = array('pending' => 'En attente...',
703 'safe' => 'Pas d\'inquiétude',
704 'unsafe' => 'Recherches en cours',
705 'dangerous' => 'Usurpations par cette adresse');
706 $page->assign('states', $states);
707
708 if (Post::has('action')) {
709 S::assert_xsrf_token();
710 }
711 switch (Post::v('action')) {
712 case 'create':
713 if (trim(Post::v('emailN')) != '') {
714 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
715 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
716 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
717 };
718 break;
719
720 case 'edit':
721 Xdb::execute('UPDATE email_watch
722 SET state = {?}, last = NOW(), uid = {?}, description = {?}
723 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
724 break;
725
726 default:
727 if ($action == 'delete' && !is_null($email)) {
728 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
729 }
730 }
731 if ($action != 'create' && $action != 'edit') {
732 $action = 'list';
733 }
734 $page->assign('action', $action);
735
736 if ($action == 'list') {
737 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
738 FROM email_watch AS w
739 LEFT JOIN emails AS e USING(email)
740 LEFT JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
741 ORDER BY w.state, w.email, a.alias";
742 $it = Xdb::iterRow($sql);
743
744 $table = array();
745 $props = array();
746 while (list($email, $date, $state, $forlife) = $it->next()) {
747 if (count($props) == 0 || $props['mail'] != $email) {
748 if (count($props) > 0) {
749 $table[] = $props;
750 }
751 $props = array('mail' => $email,
752 'detection' => $date,
753 'state' => $state,
754 'users' => array($forlife));
755 } else {
756 $props['users'][] = $forlife;
757 }
758 }
759 if (count($props) > 0) {
760 $table[] = $props;
761 }
762 $page->assign('table', $table);
763 } elseif ($action == 'edit') {
764 $sql = "SELECT w.detection, w.state, w.last, w.description,
765 a1.alias AS edit, a2.alias AS forlife
766 FROM email_watch AS w
767 LEFT JOIN aliases AS a1 ON (a1.uid = w.uid AND a1.type = 'a_vie')
768 LEFT JOIN emails AS e ON (w.email = e.email)
769 LEFT JOIN aliases AS a2 ON (a2.uid = e.uid AND a2.type = 'a_vie')
770 WHERE w.email = {?}
771 ORDER BY a2.alias";
772 $it = Xdb::iterRow($sql, $email);
773
774 $props = array();
775 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
776 if (count($props) == 0) {
777 $props = array('mail' => $email,
778 'detection' => $detection,
779 'state' => $state,
780 'last' => $last,
781 'description' => $description,
782 'edit' => $edit,
783 'users' => array($forlife));
784 } else {
785 $props['users'][] = $forlife;
786 }
787 }
788 $page->assign('doublon', $props);
789 }
790 }
791
792 function handler_lost(&$page, $action = 'list', $email = null)
793 {
794 $page->changeTpl('emails/lost.tpl');
795
796 // TODO: Order by promo.
797 $page->assign('lost_emails',
798 XDB::iterator("SELECT a.uid, a.hruid
799 FROM accounts AS a
800 INNER JOIN email_options AS eo ON (eo.uid = a.uid)
801 LEFT JOIN emails AS e ON (a.uid = e.uid AND FIND_IN_SET('active', e.flags))
802 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', eo.storage) = 0 AND
803 a.state = 'active'
804 ORDER BY a.hruid"));
805 }
806
807 function handler_broken_addr(&$page)
808 {
809 require_once 'emails.inc.php';
810 $page->changeTpl('emails/broken_addr.tpl');
811
812 if (Env::has('sort_broken')) {
813 S::assert_xsrf_token();
814
815 $list = trim(Env::v('list'));
816 if ($list == '') {
817 $page->trigError('La liste est vide.');
818 } else {
819 $valid_emails = array();
820 $invalid_emails = array();
821 $broken_list = explode("\n", $list);
822 sort($broken_list);
823 foreach ($broken_list as $orig_email) {
824 $orig_email = trim($orig_email);
825 if ($orig_email != '') {
826 $email = valide_email($orig_email);
827 if (empty($email) || $email == '@') {
828 $invalid_emails[] = trim($orig_email) . ': invalid email';
829 } elseif (!in_array($email, $valid_emails)) {
830 $res = XDB::query('SELECT COUNT(*)
831 FROM emails
832 WHERE email = {?}', $email);
833 if ($res->fetchOneCell() > 0) {
834 $valid_emails[] = $email;
835 } else {
836 $invalid_emails[] = "$orig_email: no such redirection";
837 }
838 }
839 }
840 }
841
842 $page->assign('valid_emails', $valid_emails);
843 $page->assign('invalid_emails', $invalid_emails);
844 }
845 }
846
847 if (Env::has('process_broken')) {
848 S::assert_xsrf_token();
849
850 $list = trim(Env::v('list'));
851 if ($list == '') {
852 $page->trigError('La liste est vide.');
853 } else {
854 global $platal;
855
856 $broken_user_list = array();
857 $broken_list = explode("\n", $list);
858 sort($broken_list);
859 foreach ($broken_list as $orig_email) {
860 $email = valide_email(trim($orig_email));
861 if (empty($email) || $email == '@') {
862 continue;
863 }
864
865 $sel = XDB::query(
866 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
867 acc.full_name, a.alias
868 FROM emails AS e1
869 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
870 AND e1.email != e2.email)
871 INNER JOIN accounts AS acc ON (e1.uid = acc.uid)
872 INNER JOIN aliases AS a ON (acc.uid = a.uid AND FIND_IN_SET('bestalias', a.flags))
873 WHERE e1.email = {?}
874 GROUP BY e1.uid", $email);
875
876 if ($x = $sel->fetchOneAssoc()) {
877 if (!$x['panne']) {
878 XDB::execute('UPDATE emails
879 SET panne=NOW(), last=NOW(), panne_level = 1
880 WHERE email = {?}',
881 $email);
882 } else {
883 XDB::execute('UPDATE emails
884 SET last = CURDATE(), panne_level = panne_level + 1
885 WHERE email = {?}
886 AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
887 $email);
888 }
889
890 if (!empty($x['nb_mails'])) {
891 $mail = new PlMailer('emails/broken.mail.tpl');
892 $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
893 . $globals->mail->domain . '>');
894 $mail->assign('x', $x);
895 $mail->assign('email', $email);
896 $mail->send();
897 }
898
899 if (!isset($broken_user_list[$x['alias']])) {
900 $broken_user_list[$x['alias']] = array($email);
901 } else {
902 $broken_user_list[$x['alias']][] = $email;
903 }
904 }
905 }
906
907 XDB::execute("UPDATE emails
908 SET panne_level = panne_level - 1
909 WHERE flags = 'active' AND panne_level > 1
910 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
911 XDB::execute("UPDATE emails
912 SET panne_level = 0
913 WHERE flags = 'active' AND panne_level = 1
914 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
915
916 // Output the list of users with recently broken addresses,
917 // along with the count of valid redirections.
918 require_once 'notifs.inc.php';
919 pl_content_headers("text/x-csv");
920
921 $csv = fopen('php://output', 'w');
922 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url'), ';');
923 foreach ($broken_user_list as $alias => $mails) {
924 $sel = Xdb::query(
925 "SELECT acc.uid, count(e.email) AS nb_mails,
926 IFNULL(pd.public_name, acc.full_name) AS fullname,
927 IFNULL(pd.promo, 0) AS promo
928 FROM aliases AS a
929 INNER JOIN accounts AS acc ON (a.uid = acc.uid)
930 LEFT JOIN emails AS e ON (e.uid = acc.uid
931 AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
932 LEFT JOIN account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
933 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
934 WHERE a.alias = {?}
935 GROUP BY acc.uid", $alias);
936
937 if ($x = $sel->fetchOneAssoc()) {
938 if ($x['nb_mails'] == 0) {
939 $user = User::getSilentWithUID($x['uid']);
940 $profile = $user->profile();
941 WatchProfileUpdate::register($profile, 'broken');
942 }
943 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
944 join(',', $mails), $x['nb_mails'],
945 'https://www.polytechnique.org/marketing/broken/' . $alias), ';');
946 }
947 }
948 fclose($csv);
949 exit;
950 }
951 }
952 }
953 }
954
955 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
956 ?>