Removes trailing spaces.
[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('yourself', S::user()->displayName());
623 $page->assign('sexe', S::user()->isFemale());
624 } else if (!S::logged() && $user) {
625 $storage = new EmailStorage($user, 'imap');
626 $storage->activate();
627 $page->assign('ok', true);
628 $page->assign('yourself', $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, a.hruid,
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 INNER JOIN accounts AS a ON (e1.uid = a.uid)
676 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid
677 AND FIND_IN_SET('active', e2.flags)
678 AND e1.email != e2.email)
679 WHERE e1.email = {?}
680 GROUP BY e1.uid", $email);
681 if ($x) {
682 // on écrit dans la base que l'adresse est cassée
683 if (!$x['panne']) {
684 XDB::execute("UPDATE emails
685 SET panne=NOW(), last=NOW(), panne_level = 1
686 WHERE email = {?}", $email);
687 } else {
688 XDB::execute("UPDATE emails
689 SET panne_level = 1
690 WHERE email = {?} AND panne_level = 0", $email);
691 }
692 $x['user'] = User::getWithUID($x['uid']);
693 $page->assign_by_ref('x', $x);
694 }
695 }
696 }
697 }
698
699 function handler_duplicated(&$page, $action = 'list', $email = null)
700 {
701 $page->changeTpl('emails/duplicated.tpl');
702
703 $states = array('pending' => 'En attente...',
704 'safe' => 'Pas d\'inquiétude',
705 'unsafe' => 'Recherches en cours',
706 'dangerous' => 'Usurpations par cette adresse');
707 $page->assign('states', $states);
708
709 if (Post::has('action')) {
710 S::assert_xsrf_token();
711 }
712 switch (Post::v('action')) {
713 case 'create':
714 if (trim(Post::v('emailN')) != '') {
715 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
716 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
717 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
718 };
719 break;
720
721 case 'edit':
722 Xdb::execute('UPDATE email_watch
723 SET state = {?}, last = NOW(), uid = {?}, description = {?}
724 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
725 break;
726
727 default:
728 if ($action == 'delete' && !is_null($email)) {
729 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
730 }
731 }
732 if ($action != 'create' && $action != 'edit') {
733 $action = 'list';
734 }
735 $page->assign('action', $action);
736
737 if ($action == 'list') {
738 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
739 FROM email_watch AS w
740 LEFT JOIN emails AS e USING(email)
741 LEFT JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
742 ORDER BY w.state, w.email, a.alias";
743 $it = Xdb::iterRow($sql);
744
745 $table = array();
746 $props = array();
747 while (list($email, $date, $state, $forlife) = $it->next()) {
748 if (count($props) == 0 || $props['mail'] != $email) {
749 if (count($props) > 0) {
750 $table[] = $props;
751 }
752 $props = array('mail' => $email,
753 'detection' => $date,
754 'state' => $state,
755 'users' => array($forlife));
756 } else {
757 $props['users'][] = $forlife;
758 }
759 }
760 if (count($props) > 0) {
761 $table[] = $props;
762 }
763 $page->assign('table', $table);
764 } elseif ($action == 'edit') {
765 $sql = "SELECT w.detection, w.state, w.last, w.description,
766 a1.alias AS edit, a2.alias AS forlife
767 FROM email_watch AS w
768 LEFT JOIN aliases AS a1 ON (a1.uid = w.uid AND a1.type = 'a_vie')
769 LEFT JOIN emails AS e ON (w.email = e.email)
770 LEFT JOIN aliases AS a2 ON (a2.uid = e.uid AND a2.type = 'a_vie')
771 WHERE w.email = {?}
772 ORDER BY a2.alias";
773 $it = Xdb::iterRow($sql, $email);
774
775 $props = array();
776 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
777 if (count($props) == 0) {
778 $props = array('mail' => $email,
779 'detection' => $detection,
780 'state' => $state,
781 'last' => $last,
782 'description' => $description,
783 'edit' => $edit,
784 'users' => array($forlife));
785 } else {
786 $props['users'][] = $forlife;
787 }
788 }
789 $page->assign('doublon', $props);
790 }
791 }
792
793 function handler_lost(&$page, $action = 'list', $email = null)
794 {
795 $page->changeTpl('emails/lost.tpl');
796
797 $page->assign('lost_emails',
798 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
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 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', perms))
803 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
804 WHERE e.uid IS NULL AND FIND_IN_SET(\'googleapps\', eo.storage) = 0
805 AND a.state = \'active\'
806 ORDER BY pd.promo, a.hruid'));
807 }
808
809 function handler_broken_addr(&$page)
810 {
811 require_once 'emails.inc.php';
812 $page->changeTpl('emails/broken_addr.tpl');
813
814 if (Env::has('sort_broken')) {
815 S::assert_xsrf_token();
816
817 $list = trim(Env::v('list'));
818 if ($list == '') {
819 $page->trigError('La liste est vide.');
820 } else {
821 $valid_emails = array();
822 $invalid_emails = array();
823 $broken_list = explode("\n", $list);
824 sort($broken_list);
825 foreach ($broken_list as $orig_email) {
826 $orig_email = trim($orig_email);
827 if ($orig_email != '') {
828 $email = valide_email($orig_email);
829 if (empty($email) || $email == '@') {
830 $invalid_emails[] = trim($orig_email) . ': invalid email';
831 } elseif (!in_array($email, $valid_emails)) {
832 $res = XDB::query('SELECT COUNT(*)
833 FROM emails
834 WHERE email = {?}', $email);
835 if ($res->fetchOneCell() > 0) {
836 $valid_emails[] = $email;
837 } else {
838 $invalid_emails[] = "$orig_email: no such redirection";
839 }
840 }
841 }
842 }
843
844 $page->assign('valid_emails', $valid_emails);
845 $page->assign('invalid_emails', $invalid_emails);
846 }
847 }
848
849 if (Env::has('process_broken')) {
850 S::assert_xsrf_token();
851
852 $list = trim(Env::v('list'));
853 if ($list == '') {
854 $page->trigError('La liste est vide.');
855 } else {
856 global $platal;
857
858 $broken_user_list = array();
859 $broken_list = explode("\n", $list);
860 sort($broken_list);
861 foreach ($broken_list as $orig_email) {
862 $email = valide_email(trim($orig_email));
863 if (empty($email) || $email == '@') {
864 continue;
865 }
866
867 $sel = XDB::query(
868 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
869 acc.full_name, a.alias
870 FROM emails AS e1
871 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
872 AND e1.email != e2.email)
873 INNER JOIN accounts AS acc ON (e1.uid = acc.uid)
874 INNER JOIN aliases AS a ON (acc.uid = a.uid AND FIND_IN_SET('bestalias', a.flags))
875 WHERE e1.email = {?}
876 GROUP BY e1.uid", $email);
877
878 if ($x = $sel->fetchOneAssoc()) {
879 if (!$x['panne']) {
880 XDB::execute('UPDATE emails
881 SET panne=NOW(), last=NOW(), panne_level = 1
882 WHERE email = {?}',
883 $email);
884 } else {
885 XDB::execute('UPDATE emails
886 SET last = CURDATE(), panne_level = panne_level + 1
887 WHERE email = {?}
888 AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
889 $email);
890 }
891
892 if (!empty($x['nb_mails'])) {
893 $mail = new PlMailer('emails/broken.mail.tpl');
894 $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
895 . $globals->mail->domain . '>');
896 $mail->assign('x', $x);
897 $mail->assign('email', $email);
898 $mail->send();
899 }
900
901 if (!isset($broken_user_list[$x['alias']])) {
902 $broken_user_list[$x['alias']] = array($email);
903 } else {
904 $broken_user_list[$x['alias']][] = $email;
905 }
906 }
907 }
908
909 XDB::execute("UPDATE emails
910 SET panne_level = panne_level - 1
911 WHERE flags = 'active' AND panne_level > 1
912 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
913 XDB::execute("UPDATE emails
914 SET panne_level = 0
915 WHERE flags = 'active' AND panne_level = 1
916 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
917
918 // Output the list of users with recently broken addresses,
919 // along with the count of valid redirections.
920 require_once 'notifs.inc.php';
921 pl_content_headers("text/x-csv");
922
923 $csv = fopen('php://output', 'w');
924 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url'), ';');
925 foreach ($broken_user_list as $alias => $mails) {
926 $sel = Xdb::query(
927 "SELECT acc.uid, count(e.email) AS nb_mails,
928 IFNULL(pd.public_name, acc.full_name) AS fullname,
929 IFNULL(pd.promo, 0) AS promo
930 FROM aliases AS a
931 INNER JOIN accounts AS acc ON (a.uid = acc.uid)
932 LEFT JOIN emails AS e ON (e.uid = acc.uid
933 AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
934 LEFT JOIN account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
935 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
936 WHERE a.alias = {?}
937 GROUP BY acc.uid", $alias);
938
939 if ($x = $sel->fetchOneAssoc()) {
940 if ($x['nb_mails'] == 0) {
941 $user = User::getSilentWithUID($x['uid']);
942 $profile = $user->profile();
943 WatchProfileUpdate::register($profile, 'broken');
944 }
945 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
946 join(',', $mails), $x['nb_mails'],
947 'https://www.polytechnique.org/marketing/broken/' . $alias), ';');
948 }
949 }
950 fclose($csv);
951 exit;
952 }
953 }
954 }
955 }
956
957 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
958 ?>