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 );
45 }
46
47 function handler_emails(&$page, $action = null, $email = null)
48 {
49 global $globals;
50 require_once 'emails.inc.php';
51
52 $page->changeTpl('emails/index.tpl');
53 $page->setTitle('Mes emails');
54
55 $user = S::user();
56
57 // Apply the bestalias change request.
58 if ($action == 'best' && $email) {
59 if (!S::has_xsrf_token()) {
60 return PL_FORBIDDEN;
61 }
62
63 XDB::execute("UPDATE aliases
64 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
65 WHERE id = {?}", $user->id());
66 XDB::execute("UPDATE aliases
67 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
68 WHERE id = {?} AND alias = {?}", $user->id(), $email);
69
70 // As having a non-null bestalias value is critical in
71 // plat/al's code, we do an a posteriori check on the
72 // validity of the bestalias.
73 fix_bestalias($user);
74 }
75
76 // Fetch and display aliases.
77 $sql = "SELECT alias, (type='a_vie') AS a_vie,
78 (alias REGEXP '\\\\.[0-9]{2}$') AS cent_ans,
79 FIND_IN_SET('bestalias',flags) AS best, expire
80 FROM aliases
81 WHERE id = {?} AND type!='homonyme'
82 ORDER BY LENGTH(alias)";
83 $page->assign('aliases', XDB::iterator($sql, $user->id()));
84
85 // Check for homonyms.
86 $homonyme = XDB::query(
87 "SELECT alias
88 FROM aliases
89 INNER JOIN homonymes ON (id = homonyme_id)
90 WHERE user_id = {?} AND type = 'homonyme'", $user->id());
91 $page->assign('homonyme', $homonyme->fetchOneCell());
92
93 // Display active redirections.
94 $redirect = new Redirect($user);
95 $page->assign('mails', $redirect->active_emails());
96
97 // Display, when available, the @alias_dom email alias.
98 $res = XDB::query(
99 "SELECT alias
100 FROM virtual AS v
101 INNER JOIN virtual_redirect AS vr USING(vid)
102 WHERE (redirect={?} OR redirect={?})
103 AND alias LIKE '%@{$globals->mail->alias_dom}'",
104 $user->forlifeEmail(),
105 // TODO: remove this über-ugly hack. The issue is that you need
106 // to remove all @m4x.org addresses in virtual_redirect first.
107 $user->login() . '@' . $globals->mail->domain2);
108 $page->assign('melix', $res->fetchOneCell());
109 }
110
111 function handler_alias(&$page, $action = null, $value = null)
112 {
113 require_once 'validations.inc.php';
114
115 global $globals;
116
117 $page->changeTpl('emails/alias.tpl');
118 $page->setTitle('Alias melix.net');
119
120 $user = S::user();
121 $page->assign('demande', AliasReq::get_request($user->id()));
122
123 // Remove the email alias.
124 if ($action == 'delete' && $value) {
125 S::assert_xsrf_token();
126
127 XDB::execute(
128 "DELETE virtual, virtual_redirect
129 FROM virtual
130 INNER JOIN virtual_redirect USING (vid)
131 WHERE alias = {?} AND (redirect = {?} OR redirect = {?})",
132 $value, $user->forlifeEmail(),
133 // TODO: remove this über-ugly hack. The issue is that you need
134 // to remove all @m4x.org addresses in virtual_redirect first.
135 $user->login() . '@' . $globals->mail->domain2);
136 }
137
138 // Fetch existing @alias_dom aliases.
139 $res = XDB::query(
140 "SELECT alias, emails_alias_pub
141 FROM auth_user_quick, virtual
142 INNER JOIN virtual_redirect USING(vid)
143 WHERE (redirect = {?} OR redirect = {?})
144 AND alias LIKE '%@{$globals->mail->alias_dom}' AND user_id = {?}",
145 $user->forlifeEmail(),
146 // TODO: remove this über-ugly hack. The issue is that you need
147 // to remove all @m4x.org addresses in virtual_redirect first.
148 $user->login() . '@' . $globals->mail->domain2, $user->id());
149 list($alias, $visibility) = $res->fetchOneRow();
150 $page->assign('actuel', $alias);
151
152 if ($action == 'ask' && Env::has('alias') && Env::has('raison')) {
153 S::assert_xsrf_token();
154
155 //Si l'utilisateur vient de faire une damande
156 $alias = Env::v('alias');
157 $raison = Env::v('raison');
158 $public = (Env::v('public', 'off') == 'on')?"public":"private";
159
160 $page->assign('r_alias', $alias);
161 $page->assign('r_raison', $raison);
162 if ($public == 'public') {
163 $page->assign('r_public', true);
164 }
165
166 //Quelques vérifications sur l'alias (caractères spéciaux)
167 if (!preg_match( "/^[a-zA-Z0-9\-.]{3,20}$/", $alias)) {
168 $page->trigError("L'adresse demandée n'est pas valide."
169 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
170 . " et qu'elle ne contient que des lettres non accentuées,"
171 . " des chiffres ou les caractères - et .");
172 return;
173 } else {
174 //vérifier que l'alias n'est pas déja pris
175 $res = XDB::query('SELECT COUNT(*) FROM virtual WHERE alias={?}',
176 $alias.'@'.$globals->mail->alias_dom);
177 if ($res->fetchOneCell() > 0) {
178 $page->trigError("L'alias $alias@{$globals->mail->alias_dom} a déja été attribué.
179 Tu ne peux donc pas l'obtenir.");
180 return;
181 }
182
183 //vérifier que l'alias n'est pas déja en demande
184 $it = new ValidateIterator ();
185 while($req = $it->next()) {
186 if ($req->type == "alias" and $req->alias == $alias . '@' . $globals->mail->alias_dom) {
187 $page->trigError("L'alias $alias@{$globals->mail->alias_dom} a déja été demandé.
188 Tu ne peux donc pas l'obtenir pour l'instant.");
189 return ;
190 }
191 }
192
193 //Insertion de la demande dans la base, écrase les requêtes précédente
194 $myalias = new AliasReq($user, $alias, $raison, $public);
195 $myalias->submit();
196 $page->assign('success',$alias);
197 return;
198 }
199 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
200 if (!S::has_xsrf_token()) {
201 return PL_FORBIDDEN;
202 }
203
204 if ($value == 'public') {
205 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'public'
206 WHERE user_id = {?}", $user->id());
207 } else {
208 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'private'
209 WHERE user_id = {?}", $user->id());
210 }
211
212 $visibility = $value;
213 }
214
215 $page->assign('mail_public', ($visibility == 'public'));
216 }
217
218 function handler_redirect(&$page, $action = null, $email = null)
219 {
220 global $globals;
221
222 require_once 'emails.inc.php';
223
224 $page->changeTpl('emails/redirect.tpl');
225
226 $user = S::user();
227 $page->assign_by_ref('user', $user);
228 $page->assign('eleve', $user->promo() >= date("Y") - 5);
229
230 $redirect = new Redirect($user);
231
232 // FS#703 : $_GET is urldecoded twice, hence
233 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
234 // Since there can be no spaces in emails, we can fix this with :
235 $email = str_replace(' ', '+', $email);
236
237 // Apply email redirection change requests.
238 $result = SUCCESS;
239 if ($action == 'remove' && $email) {
240 $result = $redirect->delete_email($email);
241 }
242
243 if ($action == 'active' && $email) {
244 $redirect->modify_one_email($email, true);
245 }
246
247 if ($action == 'inactive' && $email) {
248 $redirect->modify_one_email($email, false);
249 }
250
251 if ($action == 'rewrite' && $email) {
252 $rewrite = @func_get_arg(3);
253 $redirect->modify_one_email_redirect($email, $rewrite);
254 }
255
256 if (Env::has('emailop')) {
257 S::assert_xsrf_token();
258
259 $actifs = Env::v('emails_actifs', Array());
260 print_r(Env::v('emails_rewrite'));
261 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
262 $new_email = Env::v('email');
263 if ($new_email == "new@example.org") {
264 $new_email = Env::v('email_new');
265 }
266 $result = $redirect->add_email($new_email);
267 if ($result == ERROR_INVALID_EMAIL) {
268 $page->assign('email', $new_email);
269 }
270 $page->assign('retour', $result);
271 } elseif (empty($actifs)) {
272 $result = ERROR_INACTIVE_REDIRECTION;
273 } elseif (is_array($actifs)) {
274 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
275 }
276 }
277
278 switch ($result) {
279 case ERROR_INACTIVE_REDIRECTION:
280 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
281 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
282 break;
283 case ERROR_INVALID_EMAIL:
284 $page->trigError('Erreur: l\'email n\'est pas valide.');
285 break;
286 case ERROR_LOOP_EMAIL:
287 $page->trigError('Erreur : ' . $user->forlifeEmail()
288 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
289 . $globals->mail->domain2 . ' ni vers polytechnique.edu.');
290 break;
291 }
292
293 // Fetch the @alias_dom email alias, if any.
294 $res = XDB::query(
295 "SELECT alias
296 FROM virtual
297 INNER JOIN virtual_redirect USING(vid)
298 WHERE (redirect={?} OR redirect={?})
299 AND alias LIKE '%@{$globals->mail->alias_dom}'",
300 $user->forlifeEmail(),
301 // TODO: remove this über-ugly hack. The issue is that you need
302 // to remove all @m4x.org addresses in virtual_redirect first.
303 $user->login() . '@' . $globals->mail->domain2);
304 $melix = $res->fetchOneCell();
305 if ($melix) {
306 list($melix) = explode('@', $melix);
307 $page->assign('melix',$melix);
308 }
309
310 // Fetch existing email aliases.
311 $res = XDB::query(
312 "SELECT alias,expire
313 FROM aliases
314 WHERE id={?} AND (type='a_vie' OR type='alias')
315 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
316 $page->assign('alias', $res->fetchAllAssoc());
317 $page->assign('emails', $redirect->emails);
318
319 // Display GoogleApps acount information.
320 require_once 'googleapps.inc.php';
321 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
322
323 require_once 'emails.combobox.inc.php';
324 fill_email_combobox($page);
325 }
326
327 function handler_antispam(&$page, $statut_filtre = null)
328 {
329 require_once 'emails.inc.php';
330 $wp = new PlWikiPage('Xorg.Antispam');
331 $wp->buildCache();
332
333 $page->changeTpl('emails/antispam.tpl');
334
335 $bogo = new Bogo(S::user());
336 if (isset($statut_filtre)) {
337 $bogo->change($statut_filtre + 0);
338 }
339 $page->assign('filtre', $bogo->level());
340 }
341
342 function handler_submit(&$page)
343 {
344 $wp = new PlWikiPage('Xorg.Mails');
345 $wp->buildCache();
346 $page->changeTpl('emails/submit_spam.tpl');
347
348 if (Post::has('send_email')) {
349 S::assert_xsrf_token();
350
351 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
352 if (!$upload) {
353 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
354 return;
355 }
356 $mime = $upload->contentType();
357 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
358 $upload->clear();
359 $page->trigError('Le fichier ne contient pas un email complet');
360 return;
361 }
362 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
363
364 global $globals;
365 $box = $type . '@' . $globals->mail->domain;
366 $mailer = new PlMailer();
367 $mailer->addTo($box);
368 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
369 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
370 $mailer->addUploadAttachment($upload, $type . '.mail');
371 $mailer->send();
372 $page->trigSuccess('Le message a été transmis à ' . $box);
373 $upload->clear();
374 }
375 }
376
377 function handler_send(&$page)
378 {
379 $page->changeTpl('emails/send.tpl');
380 $page->addJsLink('ajax.js');
381
382 $page->setTitle('Envoyer un email');
383
384 // action si on recoit un formulaire
385 if (Post::has('save')) {
386 if (!S::has_xsrf_token()) {
387 return PL_FORBIDDEN;
388 }
389
390 unset($_POST['save']);
391 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
392 $_POST['to_contacts'] = explode(';', @$_POST['to_contacts']);
393 $_POST['cc_contacts'] = explode(';', @$_POST['cc_contacts']);
394 $data = serialize($_POST);
395 XDB::execute("REPLACE INTO email_send_save
396 VALUES ({?}, {?})", S::i('uid'), $data);
397 }
398 exit;
399 } else if (Env::v('submit') == 'Envoyer') {
400 S::assert_xsrf_token();
401
402 function getEmails($aliases)
403 {
404 if (!is_array($aliases)) {
405 return null;
406 }
407 $rel = Env::v('contacts');
408 $ret = array();
409 foreach ($aliases as $alias) {
410 $ret[$alias] = $rel[$alias];
411 }
412 return join(', ', $ret);
413 }
414
415 $error = false;
416 foreach ($_FILES as &$file) {
417 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
418 $page->trigError(PlUpload::$lastError);
419 $error = true;
420 break;
421 }
422 }
423
424 if (!$error) {
425 XDB::execute("DELETE FROM email_send_save
426 WHERE uid = {?}", S::i('uid'));
427
428 $to2 = getEmails(Env::v('to_contacts'));
429 $cc2 = getEmails(Env::v('cc_contacts'));
430 $txt = str_replace('^M', '', Env::v('contenu'));
431 $to = Env::v('to');
432 $subj = Env::v('sujet');
433 $from = Env::v('from');
434 $cc = trim(Env::v('cc'));
435 $bcc = trim(Env::v('bcc'));
436
437 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
438 $page->trigError("Indique au moins un destinataire.");
439 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
440 } else {
441 $mymail = new PlMailer();
442 $mymail->setFrom($from);
443 $mymail->setSubject($subj);
444 if (!empty($to)) { $mymail->addTo($to); }
445 if (!empty($cc)) { $mymail->addCc($cc); }
446 if (!empty($bcc)) { $mymail->addBcc($bcc); }
447 if (!empty($to2)) { $mymail->addTo($to2); }
448 if (!empty($cc2)) { $mymail->addCc($cc2); }
449 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
450 foreach ($files as $name=>&$upload) {
451 $mymail->addUploadAttachment($upload, $name);
452 }
453 if (Env::v('nowiki')) {
454 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
455 } else {
456 $mymail->setWikiBody($txt);
457 }
458 if ($mymail->send()) {
459 $page->trigSuccess("Ton email a bien été envoyé.");
460 $_REQUEST = array('bcc' => S::user()->bestEmail());
461 PlUpload::clear(S::user()->login(), 'emails.send');
462 } else {
463 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
464 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
465 }
466 }
467 }
468 } else {
469 $res = XDB::query("SELECT data
470 FROM email_send_save
471 WHERE uid = {?}", S::i('uid'));
472 if ($res->numRows() == 0) {
473 PlUpload::clear(S::user()->login(), 'emails.send');
474 $_REQUEST['bcc'] = S::user()->bestEmail();
475 } else {
476 $data = unserialize($res->fetchOneCell());
477 $_REQUEST = array_merge($_REQUEST, $data);
478 }
479 }
480
481 $res = XDB::query(
482 "SELECT u.prenom, u.nom, u.promo, a.alias as forlife
483 FROM auth_user_md5 AS u
484 INNER JOIN contacts AS c ON (u.user_id = c.contact)
485 INNER JOIN aliases AS a ON (u.user_id=a.id AND FIND_IN_SET('bestalias',a.flags))
486 WHERE c.uid = {?}
487 ORDER BY u.nom, u.prenom", S::v('uid'));
488 $page->assign('contacts', $res->fetchAllAssoc());
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.id = 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 FROM newsletter_ins WHERE user_id = {?} AND hash = {?}", $user->id(), $hash);
600 if ($req->numRows() == 0) {
601 $user = null;
602 }
603 }
604 }
605
606 require_once('emails.inc.php');
607 $page->assign('ok', false);
608 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
609 $storage = new EmailStorage(S::user(), 'imap');
610 $storage->activate();
611 $page->assign('ok', true);
612 $page->assign('prenom', S::v('prenom'));
613 $page->assign('sexe', S::v('femme'));
614 } else if (!S::logged() && $user) {
615 $storage = new EmailStorage($user, 'imap');
616 $storage->activate();
617 $page->assign('ok', true);
618 $page->assign('prenom', $user->displayName());
619 $page->assign('sexe', $user->isFemale());
620 }
621 }
622
623 function handler_broken(&$page, $warn = null, $email = null)
624 {
625 require_once 'emails.inc.php';
626 $wp = new PlWikiPage('Xorg.PatteCassée');
627 $wp->buildCache();
628
629 global $globals;
630
631 $page->changeTpl('emails/broken.tpl');
632
633 if ($warn == 'warn' && $email) {
634 S::assert_xsrf_token();
635
636 $email = valide_email($email);
637 // vérifications d'usage
638 $sel = XDB::query("SELECT uid FROM emails WHERE email = {?}", $email);
639 if (($uid = $sel->fetchOneCell())) {
640 $dest = User::getSilent($uid);
641
642 // envoi du mail
643 $message = "Bonjour !
644
645 Cet email a été généré automatiquement par le service de patte cassée de
646 Polytechnique.org car un autre utilisateur, " . S::user()->fullName() . ",
647 nous a signalé qu'en t'envoyant un email, il avait reçu un message d'erreur
648 indiquant que ton adresse de redirection $email
649 ne fonctionnait plus !
650
651 Nous te suggérons de vérifier cette adresse, et le cas échéant de mettre
652 à jour sur le site <{$globals->baseurl}/emails> tes adresses
653 de redirection...
654
655 Pour plus de renseignements sur le service de patte cassée, n'hésite pas à
656 consulter la page <{$globals->baseurl}/emails/broken>.
657
658
659 À bientôt sur Polytechnique.org !
660 L'équipe d'administration <support@" . $globals->mail->domain . '>';
661
662 $mail = new PlMailer();
663 $mail->setFrom('"Polytechnique.org" <support@' . $globals->mail->domain . '>');
664 $mail->addTo($dest->bestEmail());
665 $mail->setSubject("Une de tes adresse de redirection Polytechnique.org ne marche plus !!");
666 $mail->setTxtBody($message);
667 $mail->send();
668 $page->trigSuccess("Email envoyé !");
669 }
670 } elseif (Post::has('email')) {
671 S::assert_xsrf_token();
672
673 $email = valide_email(Post::v('email'));
674
675 list(,$fqdn) = explode('@', $email);
676 $fqdn = strtolower($fqdn);
677 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
678 $page->assign('neuneu', true);
679 } else {
680 $page->assign('email',$email);
681 $sel = XDB::query(
682 "SELECT e1.uid, e1.panne != 0 AS panne,
683 (count(e2.uid) + IF(FIND_IN_SET('googleapps', u.mail_storage), 1, 0)) AS nb_mails,
684 u.nom, u.prenom, u.promo, u.hruid
685 FROM emails as e1
686 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
687 AND FIND_IN_SET('active', e2.flags)
688 AND e1.email != e2.email)
689 INNER JOIN auth_user_md5 as u ON(e1.uid = u.user_id)
690 WHERE e1.email = {?}
691 GROUP BY e1.uid", $email);
692 if ($x = $sel->fetchOneAssoc()) {
693 // on écrit dans la base que l'adresse est cassée
694 if (!$x['panne']) {
695 XDB::execute("UPDATE emails
696 SET panne=NOW(),
697 last=NOW(),
698 panne_level = 1
699 WHERE email = {?}", $email);
700 } else {
701 XDB::execute("UPDATE emails
702 SET panne_level = 1
703 WHERE email = {?} AND panne_level = 0", $email);
704 }
705 $page->assign_by_ref('x', $x);
706 }
707 }
708 }
709 }
710
711 function handler_duplicated(&$page, $action = 'list', $email = null)
712 {
713 $page->changeTpl('emails/duplicated.tpl');
714
715 $states = array('pending' => 'En attente...',
716 'safe' => 'Pas d\'inquiétude',
717 'unsafe' => 'Recherches en cours',
718 'dangerous' => 'Usurpations par cette adresse');
719 $page->assign('states', $states);
720
721 if (Post::has('action')) {
722 S::assert_xsrf_token();
723 }
724 switch (Post::v('action')) {
725 case 'create':
726 if (trim(Post::v('emailN')) != '') {
727 Xdb::execute('INSERT IGNORE INTO emails_watch (email, state, detection, last, uid, description)
728 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
729 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
730 };
731 break;
732
733 case 'edit':
734 Xdb::execute('UPDATE emails_watch
735 SET state = {?}, last = NOW(), uid = {?}, description = {?}
736 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
737 break;
738
739 default:
740 if ($action == 'delete' && !is_null($email)) {
741 Xdb::execute('DELETE FROM emails_watch WHERE email = {?}', $email);
742 }
743 }
744 if ($action != 'create' && $action != 'edit') {
745 $action = 'list';
746 }
747 $page->assign('action', $action);
748
749 if ($action == 'list') {
750 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
751 FROM emails_watch AS w
752 LEFT JOIN emails AS e USING(email)
753 LEFT JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
754 ORDER BY w.state, w.email, a.alias";
755 $it = Xdb::iterRow($sql);
756
757 $table = array();
758 $props = array();
759 while (list($email, $date, $state, $forlife) = $it->next()) {
760 if (count($props) == 0 || $props['mail'] != $email) {
761 if (count($props) > 0) {
762 $table[] = $props;
763 }
764 $props = array('mail' => $email,
765 'detection' => $date,
766 'state' => $state,
767 'users' => array($forlife));
768 } else {
769 $props['users'][] = $forlife;
770 }
771 }
772 if (count($props) > 0) {
773 $table[] = $props;
774 }
775 $page->assign('table', $table);
776 } elseif ($action == 'edit') {
777 $sql = "SELECT w.detection, w.state, w.last, w.description,
778 a1.alias AS edit, a2.alias AS forlife
779 FROM emails_watch AS w
780 LEFT JOIN aliases AS a1 ON (a1.id = w.uid AND a1.type = 'a_vie')
781 LEFT JOIN emails AS e ON (w.email = e.email)
782 LEFT JOIN aliases AS a2 ON (a2.id = e.uid AND a2.type = 'a_vie')
783 WHERE w.email = {?}
784 ORDER BY a2.alias";
785 $it = Xdb::iterRow($sql, $email);
786
787 $props = array();
788 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
789 if (count($props) == 0) {
790 $props = array('mail' => $email,
791 'detection' => $detection,
792 'state' => $state,
793 'last' => $last,
794 'description' => $description,
795 'edit' => $edit,
796 'users' => array($forlife));
797 } else {
798 $props['users'][] = $forlife;
799 }
800 }
801 $page->assign('doublon', $props);
802 }
803 }
804 function handler_lost(&$page, $action = 'list', $email = null)
805 {
806 $page->changeTpl('emails/lost.tpl');
807
808 $page->assign('lost_emails', XDB::iterator("
809 SELECT u.user_id, u.hruid
810 FROM auth_user_md5 AS u
811 LEFT JOIN emails AS e ON (u.user_id = e.uid AND FIND_IN_SET('active', e.flags))
812 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', u.mail_storage) = 0 AND
813 u.deces = 0 AND u.perms IN ('user', 'admin', 'disabled')
814 ORDER BY u.promo DESC, u.nom, u.prenom"));
815 }
816 }
817
818 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
819 ?>