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