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