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