Allows antispam level choice for each redirection.
[platal.git] / modules / email.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class EmailModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'emails' => $this->make_hook('emails', AUTH_COOKIE, 'mail'),
28 'emails/alias' => $this->make_hook('alias', AUTH_MDP, 'mail'),
29 'emails/antispam' => $this->make_hook('antispam', AUTH_MDP, 'mail'),
30 'emails/broken' => $this->make_hook('broken', AUTH_COOKIE),
31 'emails/redirect' => $this->make_hook('redirect', AUTH_MDP, 'mail'),
32 'emails/send' => $this->make_hook('send', AUTH_MDP, 'mail'),
33 'emails/antispam/submit' => $this->make_hook('submit', AUTH_COOKIE),
34 'emails/test' => $this->make_hook('test', AUTH_COOKIE, 'mail', NO_AUTH),
35
36 'emails/rewrite/in' => $this->make_hook('rewrite_in', AUTH_PUBLIC),
37 'emails/rewrite/out' => $this->make_hook('rewrite_out', AUTH_PUBLIC),
38
39 'emails/imap/in' => $this->make_hook('imap_in', AUTH_PUBLIC),
40
41 'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
42 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
43 'admin/emails/lost' => $this->make_hook('lost', AUTH_MDP, 'admin'),
44 'admin/emails/broken' => $this->make_hook('broken_addr', AUTH_MDP, 'admin'),
45 );
46 }
47
48 function handler_emails($page, $action = null, $email = null)
49 {
50 global $globals;
51 require_once 'emails.inc.php';
52
53 $page->changeTpl('emails/index.tpl');
54 $page->setTitle('Mes emails');
55
56 $user = S::user();
57
58 // Apply the bestalias change request.
59 if ($action == 'best' && $email) {
60 if (!S::has_xsrf_token()) {
61 return PL_FORBIDDEN;
62 }
63
64 // First delete the bestalias flag from all this user's emails.
65 XDB::execute("UPDATE email_source_account
66 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
67 WHERE uid = {?}", $user->id());
68 // Then gives the bestalias flag to the given email.
69 list($email, $domain) = explode('@', $email);
70 XDB::execute("UPDATE email_source_account AS s
71 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
72 SET s.flags = CONCAT_WS(',', IF(s.flags = '', NULL, s.flags), 'bestalias')
73 WHERE s.uid = {?} AND s.email = {?} AND d.name = {?}", $user->id(), $email, $domain);
74
75 // As having a non-null bestalias value is critical in
76 // plat/al's code, we do an a posteriori check on the
77 // validity of the bestalias.
78 fix_bestalias($user);
79 }
80
81 // Fetch and display aliases.
82 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
83 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
84 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
85 (d.name = {?}) AS alias
86 FROM email_source_account AS s
87 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
88 WHERE s.uid = {?}
89 ORDER BY !alias, s.email",
90 $globals->mail->alias_dom, $user->id());
91 $page->assign('aliases', $aliases);
92
93 $alias = XDB::fetchOneCell('SELECT COUNT(s.email)
94 FROM email_source_account AS s
95 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
96 WHERE s.uid = {?} AND d.name = {?}',
97 $user->id(), $globals->mail->alias_dom);
98 $page->assign('alias', $alias);
99
100
101 // Check for homonyms.
102 $page->assign('homonyme', $user->homonyme);
103
104 // Display active redirections.
105 $redirect = new Redirect($user);
106 $page->assign('mails', $redirect->active_emails());
107 }
108
109 function handler_alias($page, $action = null, $value = null)
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('request', AliasReq::get_request($user->id()));
118
119 // Remove the email alias.
120 if ($action == 'delete') {
121 S::assert_xsrf_token();
122
123 XDB::execute('DELETE s
124 FROM email_source_account AS s
125 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
126 WHERE s.uid = {?} AND d.name = {?}',
127 $user->id(), $globals->mail->alias_dom);
128
129 require_once 'emails.inc.php';
130 fix_bestalias($user);
131 }
132
133 // Fetch existing @alias_dom aliases.
134 list($alias, $old_alias) = XDB::fetchOneRow('SELECT CONCAT(s.email, \'@\', d.name), s.email
135 FROM email_source_account AS s
136 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
137 WHERE s.uid = {?} AND d.name = {?}',
138 $user->id(), $globals->mail->alias_dom);
139 $visibility = $user->hasProfile() && ($user->profile(true)->alias_pub == 'public');
140 $page->assign('current', $alias);
141 $page->assign('user', $user);
142 $page->assign('mail_public', $visibility);
143
144 if ($action == 'ask' && Env::has('alias') && Env::has('reason')) {
145 S::assert_xsrf_token();
146
147 // Retrieves user request.
148 $new_alias = Env::v('alias');
149 $reason = Env::v('reason');
150 $public = (Env::v('public', 'off') == 'on') ? 'public' : 'private';
151
152 $page->assign('r_alias', $new_alias);
153 $page->assign('r_reason', $reason);
154 if ($public == 'public') {
155 $page->assign('r_public', true);
156 }
157
158 // Checks special charaters in alias.
159 if (!preg_match("/^[a-zA-Z0-9\-.]{3,20}$/", $new_alias)) {
160 $page->trigError("L'adresse demandée n'est pas valide."
161 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
162 . " et qu'elle ne contient que des lettres non accentuées,"
163 . " des chiffres ou les caractères - et .");
164 return;
165 } else {
166 // Checks if the alias has already been given.
167 $res = XDB::query('SELECT COUNT(s.email)
168 FROM email_source_account AS s
169 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
170 WHERE s.email = {?} AND d.name = {?}',
171 $new_alias, $globals->mail->alias_dom);
172 if ($res->fetchOneCell() > 0) {
173 $page->trigError("L'alias $new_alias a déja été attribué. Tu ne peux donc pas l'obtenir.");
174 return;
175 }
176
177 // Checks if the alias has already been asked for.
178 $it = Validate::iterate('alias');
179 while($req = $it->next()) {
180 if ($req->alias == $new_alias) {
181 $page->trigError("L'alias $new_alias a déja été demandé. Tu ne peux donc pas l'obtenir pour l'instant.");
182 return;
183 }
184 }
185
186 // Sends requests. This will erase any previous alias pending request.
187 $myalias = new AliasReq($user, $new_alias, $reason, $public, $old_alias);
188 $myalias->submit();
189 $page->assign('success', $new_alias);
190 return;
191 }
192 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
193 if (!S::has_xsrf_token()) {
194 return PL_FORBIDDEN;
195 }
196
197 if ($user->hasProfile()) {
198 XDB::execute('UPDATE profiles
199 SET alias_pub = {?}
200 WHERE pid = {?}',
201 $value, $user->profile()->id());
202 }
203 exit;
204 }
205 }
206
207 function handler_redirect($page, $action = null, $email = null, $rewrite = null)
208 {
209 global $globals;
210 require_once 'emails.inc.php';
211
212 $page->changeTpl('emails/redirect.tpl');
213
214 $user = S::user();
215 $page->assign_by_ref('user', $user);
216 $page->assign('eleve', $user->promo() >= date("Y") - 5);
217
218 $redirect = new Redirect($user);
219
220 // FS#703 : $_GET is urldecoded twice, hence
221 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
222 // Since there can be no spaces in emails, we can fix this with :
223 $email = str_replace(' ', '+', $email);
224
225 // Apply email redirection change requests.
226 $result = SUCCESS;
227 if ($action == 'remove' && $email) {
228 $result = $redirect->delete_email($email);
229 }
230
231 if ($action == 'active' && $email) {
232 $redirect->modify_one_email($email, true);
233 }
234
235 if ($action == 'inactive' && $email) {
236 $redirect->modify_one_email($email, false);
237 }
238
239 if ($action == 'rewrite' && $email) {
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 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
248 $error_email = false;
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 $error_email = true;
256 $page->assign('email', $new_email);
257 }
258 $page->assign('retour', $result);
259 $page->assign('error_email', $error_email);
260 } elseif (empty($actifs)) {
261 $result = ERROR_INACTIVE_REDIRECTION;
262 } elseif (is_array($actifs)) {
263 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', array()));
264 }
265 }
266
267 switch ($result) {
268 case ERROR_INACTIVE_REDIRECTION:
269 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
270 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
271 break;
272 case ERROR_INVALID_EMAIL:
273 $page->trigError('Erreur : l\'email n\'est pas valide.');
274 break;
275 case ERROR_LOOP_EMAIL:
276 $page->trigError('Erreur : ' . $user->forlifeEmail()
277 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
278 . $globals->mail->domain2 . ' ni vers polytechnique.edu.');
279 break;
280 }
281 // Fetch existing email aliases.
282 $alias = XDB::query('SELECT CONCAT(s.email, \'@\', d.name) AS email, s.expire
283 FROM email_source_account AS s
284 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
285 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
286 WHERE s.uid = {?}
287 ORDER BY NOT (m.name = {?}), s.email, d.name',
288 $user->id(), $globals->mail->alias_dom);
289 $page->assign('alias', $alias->fetchAllAssoc());
290
291 $page->assign('emails', $redirect->emails);
292
293 // Display GoogleApps acount information.
294 require_once 'googleapps.inc.php';
295 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
296
297 require_once 'emails.combobox.inc.php';
298 fill_email_combobox($page);
299 }
300
301 function handler_antispam($page, $filter_status = null, $redirection = null)
302 {
303 require_once 'emails.inc.php';
304 $wp = new PlWikiPage('Xorg.Antispam');
305 $wp->buildCache();
306
307 $page->changeTpl('emails/antispam.tpl');
308
309 $user = S::user();
310 $bogo = new Bogo($user);
311 if (!is_null($filter_status)) {
312 if (is_null($redirection)) {
313 $bogo->changeAll($filter_status);
314 } else {
315 $bogo->change($redirection, $filter_status);
316 }
317 }
318 $page->assign('filter', $bogo->state);
319 $page->assign('single_state', $bogo->single_state);
320 $page->assign('single_redirection', $bogo->single_redirection);
321 $page->assign('redirections', $bogo->redirections);
322 }
323
324 function handler_submit($page)
325 {
326 $wp = new PlWikiPage('Xorg.Mails');
327 $wp->buildCache();
328 $page->changeTpl('emails/submit_spam.tpl');
329
330 if (Post::has('send_email')) {
331 S::assert_xsrf_token();
332
333 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
334 if (!$upload) {
335 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
336 return;
337 }
338 $mime = $upload->contentType();
339 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
340 $upload->clear();
341 $page->trigError('Le fichier ne contient pas un email complet');
342 return;
343 }
344 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
345
346 global $globals;
347 $box = $type . '@' . $globals->mail->domain;
348 $mailer = new PlMailer();
349 $mailer->addTo($box);
350 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
351 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
352 $mailer->addUploadAttachment($upload, $type . '.mail');
353 $mailer->send();
354 $page->trigSuccess('Le message a été transmis à ' . $box);
355 $upload->clear();
356 }
357 }
358
359 function handler_send($page)
360 {
361 $page->changeTpl('emails/send.tpl');
362
363 $page->setTitle('Envoyer un email');
364
365 // action si on recoit un formulaire
366 if (Post::has('save')) {
367 if (!S::has_xsrf_token()) {
368 return PL_FORBIDDEN;
369 }
370
371 unset($_POST['save']);
372 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
373 Post::set('to_contacts', explode(';', Post::s('to_contacts')));
374 Post::set('cc_contacts', explode(';', Post::s('cc_contacts')));
375 $data = serialize($_POST);
376 XDB::execute('INSERT INTO email_send_save (uid, data)
377 VALUES ({?}, {?})
378 ON DUPLICATE KEY UPDATE data = VALUES(data)',
379 S::user()->id('uid'), $data);
380 }
381 exit;
382 } else if (Env::v('submit') == 'Envoyer') {
383 S::assert_xsrf_token();
384
385 function getEmails($aliases)
386 {
387 if (!is_array($aliases)) {
388 return null;
389 }
390 $uf = new UserFilter(new UFC_Hrpid($aliases));
391 $users = $uf->iterUsers();
392 $ret = array();
393 while ($user = $users->next()) {
394 $ret[] = $user->forlife;
395 }
396 return join(', ', $ret);
397 }
398
399 $error = false;
400 foreach ($_FILES as &$file) {
401 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
402 $page->trigError(PlUpload::$lastError);
403 $error = true;
404 break;
405 }
406 }
407
408 if (!$error) {
409 XDB::execute("DELETE FROM email_send_save
410 WHERE uid = {?}",
411 S::user()->id());
412
413 $to2 = getEmails(Env::v('to_contacts'));
414 $cc2 = getEmails(Env::v('cc_contacts'));
415 $txt = str_replace('^M', '', Env::v('contenu'));
416 $to = str_replace(';', ',', Env::t('to'));
417 $subj = Env::t('sujet');
418 $from = Env::t('from');
419 $cc = str_replace(';', ',', Env::t('cc'));
420 $bcc = str_replace(';', ',', Env::t('bcc'));
421
422 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
423 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
424 $email = trim($email);
425 if ($email != '' && !preg_match($email_regex, $email)) {
426 $page->trigError("L'adresse email " . $email . ' est erronée.');
427 $error = true;
428 }
429 }
430 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
431 $page->trigError("Indique au moins un destinataire.");
432 $error = true;
433 }
434
435 if ($error) {
436 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
437 } else {
438 $mymail = new PlMailer();
439 $mymail->setFrom($from);
440 $mymail->setSubject($subj);
441 if (!empty($to)) { $mymail->addTo($to); }
442 if (!empty($cc)) { $mymail->addCc($cc); }
443 if (!empty($bcc)) { $mymail->addBcc($bcc); }
444 if (!empty($to2)) { $mymail->addTo($to2); }
445 if (!empty($cc2)) { $mymail->addCc($cc2); }
446 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
447 foreach ($files as $name=>&$upload) {
448 $mymail->addUploadAttachment($upload, $name);
449 }
450 if (Env::v('nowiki')) {
451 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
452 } else {
453 $mymail->setWikiBody($txt);
454 }
455 if ($mymail->send()) {
456 $page->trigSuccess("Ton email a bien été envoyé.");
457 $_REQUEST = array('bcc' => S::user()->bestEmail());
458 PlUpload::clear(S::user()->login(), 'emails.send');
459 } else {
460 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
461 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
462 }
463 }
464 }
465 } else {
466 $res = XDB::query("SELECT data
467 FROM email_send_save
468 WHERE uid = {?}", S::i('uid'));
469 if ($res->numRows() == 0) {
470 PlUpload::clear(S::user()->login(), 'emails.send');
471 $_REQUEST['bcc'] = S::user()->bestEmail();
472 } else {
473 $data = unserialize($res->fetchOneCell());
474 $_REQUEST = array_merge($_REQUEST, $data);
475 }
476 }
477
478 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
479 new UFC_Registered()),
480 UserFilter::sortByName());
481 $contacts = $uf->getProfiles();
482 $page->assign('contacts', $contacts);
483 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
484 $page->assign('user', S::user());
485 }
486
487 function handler_test($page, $hruid = null)
488 {
489 require_once 'emails.inc.php';
490
491 if (!S::has_xsrf_token()) {
492 return PL_FORBIDDEN;
493 }
494
495 // Retrieves the User object for the test email recipient.
496 if (S::admin() && $hruid) {
497 $user = User::getSilent($hruid);
498 } else {
499 $user = S::user();
500 }
501 if (!$user) {
502 return PL_NOT_FOUND;
503 }
504
505 // Sends the test email.
506 $redirect = new Redirect($user);
507
508 $mailer = new PlMailer('emails/test.mail.tpl');
509 $mailer->assign('email', $user->bestEmail());
510 $mailer->assign('redirects', $redirect->active_emails());
511 $mailer->assign('display_name', $user->displayName());
512 $mailer->assign('sexe', $user->isFemale());
513 $mailer->send($user->isEmailFormatHtml());
514 exit;
515 }
516
517 function handler_rewrite_in($page, $mail, $hash)
518 {
519 $page->changeTpl('emails/rewrite.tpl');
520 $page->assign('option', 'in');
521 if (empty($mail) || empty($hash)) {
522 return PL_NOT_FOUND;
523 }
524 $pos = strrpos($mail, '_');
525 if ($pos === false) {
526 return PL_NOT_FOUND;
527 }
528 $mail{$pos} = '@';
529 $res = XDB::query('SELECT COUNT(*)
530 FROM email_redirect_account
531 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
532 $mail, $hash);
533 $count = intval($res->fetchOneCell());
534 if ($count > 0) {
535 XDB::query('UPDATE email_redirect_account
536 SET allow_rewrite = true, hash = NULL
537 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
538 $mail, $hash);
539 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
540 return;
541 }
542 return PL_NOT_FOUND;
543 }
544
545 function handler_rewrite_out($page, $mail, $hash)
546 {
547 $page->changeTpl('emails/rewrite.tpl');
548 $page->assign('option', 'out');
549 if (empty($mail) || empty($hash)) {
550 return PL_NOT_FOUND;
551 }
552 $pos = strrpos($mail, '_');
553 if ($pos === false) {
554 return PL_NOT_FOUND;
555 }
556 $mail{$pos} = '@';
557 $res = XDB::query('SELECT COUNT(*)
558 FROM email_redirect_account
559 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
560 $mail, $hash);
561 $count = intval($res->fetchOneCell());
562 if ($count > 0) {
563 global $globals;
564 $res = XDB::query('SELECT e.redirect, e.rewrite, a.hruid
565 FROM email_redirect_account AS e
566 INNER JOIN accounts AS a ON (e.uid = a.uid)
567 WHERE e.redirect = {?} AND e.hash = {?}',
568 $mail, $hash);
569 XDB::query('UPDATE email_redirect_account
570 SET allow_rewrite = false, hash = NULL
571 WHERE redirect = {?} AND hash = {?}',
572 $mail, $hash);
573 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
574 $mail = new PlMailer();
575 $mail->setFrom("webmaster@" . $globals->mail->domain);
576 $mail->addTo("support@" . $globals->mail->domain);
577 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
578 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
579 $mail->send();
580 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
581 return;
582 }
583 return PL_NOT_FOUND;
584 }
585
586 function handler_imap_in($page, $hash = null, $login = null)
587 {
588 $page->changeTpl('emails/imap_register.tpl');
589 $user = null;
590 if (!empty($hash) || !empty($login)) {
591 $user = User::getSilent($login);
592 if ($user) {
593 $req = XDB::query('SELECT 1
594 FROM newsletter_ins
595 WHERE uid = {?} AND hash = {?}',
596 $user->id(), $hash);
597 if ($req->numRows() == 0) {
598 $user = null;
599 }
600 }
601 }
602
603 require_once 'emails.inc.php';
604 $page->assign('ok', false);
605 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
606 Email::activate_storage(S::user(), 'imap');
607 $page->assign('ok', true);
608 $page->assign('yourself', S::user()->displayName());
609 $page->assign('sexe', S::user()->isFemale());
610 } else if (!S::logged() && $user) {
611 Email::activate_storage($user, 'imap');
612 $page->assign('ok', true);
613 $page->assign('yourself', $user->displayName());
614 $page->assign('sexe', $user->isFemale());
615 }
616 }
617
618 function handler_broken($page, $warn = null, $email = null)
619 {
620 require_once 'emails.inc.php';
621 $wp = new PlWikiPage('Xorg.PatteCassée');
622 $wp->buildCache();
623
624 global $globals;
625
626 $page->changeTpl('emails/broken.tpl');
627
628 if ($warn == 'warn' && $email) {
629 S::assert_xsrf_token();
630
631 // Usual verifications.
632 $email = valide_email($email);
633 $uid = XDB::fetchOneCell('SELECT uid
634 FROM email_redirect_account
635 WHERE redirect = {?}', $email);
636
637 if ($uid) {
638 $dest = User::getWithUID($uid);
639
640 $mail = new PlMailer('emails/broken-web.mail.tpl');
641 $mail->assign('email', $email);
642 $mail->assign('request', S::user());
643 $mail->sendTo($dest);
644 $page->trigSuccess('Email envoyé&nbsp;!');
645 }
646 } elseif (Post::has('email')) {
647 S::assert_xsrf_token();
648
649 $email = Post::t('email');
650 list(, $domain) = explode('@', $email);
651 $domain = strtolower($domain);
652
653 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2
654 || $domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
655 $page->assign('neuneu', true);
656 } else {
657 $user = mark_broken_email($email);
658 $page->assign('user', $user);
659 $page->assign('email', $email);
660 }
661 }
662 }
663
664 function handler_duplicated($page, $action = 'list', $email = null)
665 {
666 $page->changeTpl('emails/duplicated.tpl');
667
668 $states = array('pending' => 'En attente...',
669 'safe' => 'Pas d\'inquiétude',
670 'unsafe' => 'Recherches en cours',
671 'dangerous' => 'Usurpations par cette adresse');
672 $page->assign('states', $states);
673
674 if (Post::has('action')) {
675 S::assert_xsrf_token();
676 }
677 switch (Post::v('action')) {
678 case 'create':
679 if (trim(Post::v('emailN')) != '') {
680 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
681 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
682 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
683 };
684 break;
685
686 case 'edit':
687 Xdb::execute('UPDATE email_watch
688 SET state = {?}, last = NOW(), uid = {?}, description = {?}
689 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
690 break;
691
692 default:
693 if ($action == 'delete' && !is_null($email)) {
694 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
695 }
696 }
697 if ($action != 'create' && $action != 'edit') {
698 $action = 'list';
699 }
700 $page->assign('action', $action);
701
702 if ($action == 'list') {
703 $it = XDB::iterRow('SELECT w.email, w.detection, w.state, s.email AS forlife
704 FROM email_watch AS w
705 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
706 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
707 ORDER BY w.state, w.email, s.email');
708
709 $table = array();
710 $props = array();
711 while (list($email, $date, $state, $forlife) = $it->next()) {
712 if (count($props) == 0 || $props['mail'] != $email) {
713 if (count($props) > 0) {
714 $table[] = $props;
715 }
716 $props = array('mail' => $email,
717 'detection' => $date,
718 'state' => $state,
719 'users' => array($forlife));
720 } else {
721 $props['users'][] = $forlife;
722 }
723 }
724 if (count($props) > 0) {
725 $table[] = $props;
726 }
727 $page->assign('table', $table);
728 } elseif ($action == 'edit') {
729 $it = XDB::iterRow('SELECT w.detection, w.state, w.last, w.description,
730 a.hruid AS edit, s.email AS forlife
731 FROM email_watch AS w
732 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
733 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
734 INNER JOIN accounts AS a ON (w.uid = a.uid)
735 WHERE w.email = {?}
736 ORDER BY s.email',
737 $email);
738
739 $props = array();
740 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
741 if (count($props) == 0) {
742 $props = array('mail' => $email,
743 'detection' => $detection,
744 'state' => $state,
745 'last' => $last,
746 'description' => $description,
747 'edit' => $edit,
748 'users' => array($forlife));
749 } else {
750 $props['users'][] = $forlife;
751 }
752 }
753 $page->assign('doublon', $props);
754 }
755 }
756
757 function handler_lost($page, $action = 'list', $email = null)
758 {
759 $page->changeTpl('emails/lost.tpl');
760
761 $page->assign('lost_emails',
762 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
763 FROM accounts AS a
764 INNER JOIN account_types AS at ON (a.type = at.type)
765 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
766 AND er.type != \'imap\' AND er.type != \'homonym\')
767 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
768 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
769 WHERE a.state = \'active\' AND er.redirect IS NULL AND FIND_IN_SET(\'mail\', at.perms)
770 GROUP BY a.uid
771 ORDER BY pd.promo, a.hruid'));
772 }
773
774 function handler_broken_addr($page)
775 {
776 require_once 'emails.inc.php';
777 $page->changeTpl('emails/broken_addr.tpl');
778
779 if (Env::has('sort_broken')) {
780 S::assert_xsrf_token();
781
782 $list = trim(Env::v('list'));
783 if ($list == '') {
784 $page->trigError('La liste est vide.');
785 } else {
786 $valid_emails = array();
787 $invalid_emails = array();
788 $broken_list = explode("\n", $list);
789 sort($broken_list);
790 foreach ($broken_list as $orig_email) {
791 $orig_email = trim($orig_email);
792 if ($orig_email != '') {
793 $email = valide_email($orig_email);
794 if (empty($email) || $email == '@') {
795 $invalid_emails[] = trim($orig_email) . ': invalid email';
796 } elseif (!in_array($email, $valid_emails)) {
797 $nb = XDB::fetchOneCell('SELECT COUNT(*)
798 FROM email_redirect_account
799 WHERE redirect = {?}', $email);
800 if ($nb > 0) {
801 $valid_emails[] = $email;
802 } else {
803 $invalid_emails[] = $orig_email . ': no such redirection';
804 }
805 }
806 }
807 }
808
809 $page->assign('valid_emails', $valid_emails);
810 $page->assign('invalid_emails', $invalid_emails);
811 }
812 }
813
814 if (Env::has('process_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 $broken_user_list = array();
822 $broken_list = explode("\n", $list);
823 sort($broken_list);
824
825 foreach ($broken_list as $email) {
826 if ($user = mark_broken_email($email, true)) {
827 if ($user['nb_mails'] > 0) {
828 $mail = new PlMailer('emails/broken.mail.tpl');
829 $mail->addTo('"' . $user['full_name'] . '" <' . $user['alias'] . '@' . Platal::globals()->mail->domain . '>');
830 $mail->assign('user', $user);
831 $mail->assign('email', $email);
832 $mail->send();
833 }
834
835 if (!isset($broken_user_list[$user['alias']])) {
836 $broken_user_list[$user['alias']] = array($email);
837 } else {
838 $broken_user_list[$user['alias']][] = $email;
839 }
840 }
841 }
842
843 XDB::execute('UPDATE email_redirect_account
844 SET broken_level = broken_level - 1
845 WHERE flags = \'active\' AND broken_level > 1
846 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()');
847 XDB::execute('UPDATE email_redirect_account
848 SET broken_level = 0
849 WHERE flags = \'active\' AND broken_level = 1
850 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()');
851
852 // Output the list of users with recently broken addresses,
853 // along with the count of valid redirections.
854 require_once 'notifs.inc.php';
855 pl_cached_content_headers('text/x-csv', 1);
856
857 $csv = fopen('php://output', 'w');
858 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
859 foreach ($broken_user_list as $alias => $mails) {
860 $sel = Xdb::query(
861 'SELECT a.uid, count(DISTINCT(r.redirect)) AS nb_mails,
862 IFNULL(pd.public_name, a.full_name) AS fullname,
863 IFNULL(pd.promo, 0) AS promo, IFNULL(pce.name, \'Aucun\') AS corps,
864 IFNULL(pje.name, \'Aucun\') AS job, GROUP_CONCAT(pn.address SEPARATOR \', \') AS networking
865 FROM email_source_account AS s
866 INNER JOIN accounts AS a ON (s.uid = a.uid)
867 LEFT JOIN email_redirect_account AS r ON (a.uid = r.uid AND r.broken_level = 0 AND r.flags = \'active\' AND
868 (r.type = \'smtp\' OR r.type = \'googleapps\'))
869 LEFT JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
870 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
871 LEFT JOIN profile_corps AS pc ON (pc.pid = ap.pid)
872 LEFT JOIN profile_corps_enum AS pce ON (pc.current_corpsid = pce.id)
873 LEFT JOIN profile_job AS pj ON (pj.pid = ap.pid)
874 LEFT JOIN profile_job_enum AS pje ON (pj.jobid = pje.id)
875 LEFT JOIN profile_networking AS pn ON (pn.pid = ap.pid)
876 WHERE s.email = {?}
877 GROUP BY a.uid', $alias);
878
879 if ($x = $sel->fetchOneAssoc()) {
880 if ($x['nb_mails'] == 0) {
881 $user = User::getSilentWithUID($x['uid']);
882 $profile = $user->profile();
883 WatchProfileUpdate::register($profile, 'broken');
884 }
885 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
886 join(',', $mails), $x['nb_mails'],
887 'https://www.polytechnique.org/marketing/broken/' . $alias,
888 $x['corps'], $x['job'], $x['networking']), ';');
889 }
890 }
891 fclose($csv);
892 exit;
893 }
894 }
895 }
896 }
897
898 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
899 ?>