b0bb9429a045b945b1de1fc47775e78716e6b02b
[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)
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 (isset($filter_status)) {
312 $bogo->change($filter_status + 0);
313 }
314 $page->assign('filter', $bogo->level());
315 }
316
317 function handler_submit($page)
318 {
319 $wp = new PlWikiPage('Xorg.Mails');
320 $wp->buildCache();
321 $page->changeTpl('emails/submit_spam.tpl');
322
323 if (Post::has('send_email')) {
324 S::assert_xsrf_token();
325
326 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
327 if (!$upload) {
328 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
329 return;
330 }
331 $mime = $upload->contentType();
332 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
333 $upload->clear();
334 $page->trigError('Le fichier ne contient pas un email complet');
335 return;
336 }
337 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
338
339 global $globals;
340 $box = $type . '@' . $globals->mail->domain;
341 $mailer = new PlMailer();
342 $mailer->addTo($box);
343 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
344 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
345 $mailer->addUploadAttachment($upload, $type . '.mail');
346 $mailer->send();
347 $page->trigSuccess('Le message a été transmis à ' . $box);
348 $upload->clear();
349 }
350 }
351
352 function handler_send($page)
353 {
354 $page->changeTpl('emails/send.tpl');
355
356 $page->setTitle('Envoyer un email');
357
358 // action si on recoit un formulaire
359 if (Post::has('save')) {
360 if (!S::has_xsrf_token()) {
361 return PL_FORBIDDEN;
362 }
363
364 unset($_POST['save']);
365 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
366 Post::set('to_contacts', explode(';', Post::s('to_contacts')));
367 Post::set('cc_contacts', explode(';', Post::s('cc_contacts')));
368 $data = serialize($_POST);
369 XDB::execute('INSERT INTO email_send_save (uid, data)
370 VALUES ({?}, {?})
371 ON DUPLICATE KEY UPDATE data = VALUES(data)',
372 S::user()->id('uid'), $data);
373 }
374 exit;
375 } else if (Env::v('submit') == 'Envoyer') {
376 S::assert_xsrf_token();
377
378 function getEmails($aliases)
379 {
380 if (!is_array($aliases)) {
381 return null;
382 }
383 $uf = new UserFilter(new UFC_Hrpid($aliases));
384 $users = $uf->iterUsers();
385 $ret = array();
386 while ($user = $users->next()) {
387 $ret[] = $user->forlife;
388 }
389 return join(', ', $ret);
390 }
391
392 $error = false;
393 foreach ($_FILES as &$file) {
394 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
395 $page->trigError(PlUpload::$lastError);
396 $error = true;
397 break;
398 }
399 }
400
401 if (!$error) {
402 XDB::execute("DELETE FROM email_send_save
403 WHERE uid = {?}",
404 S::user()->id());
405
406 $to2 = getEmails(Env::v('to_contacts'));
407 $cc2 = getEmails(Env::v('cc_contacts'));
408 $txt = str_replace('^M', '', Env::v('contenu'));
409 $to = str_replace(';', ',', Env::t('to'));
410 $subj = Env::t('sujet');
411 $from = Env::t('from');
412 $cc = str_replace(';', ',', Env::t('cc'));
413 $bcc = str_replace(';', ',', Env::t('bcc'));
414
415 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
416 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
417 $email = trim($email);
418 if ($email != '' && !preg_match($email_regex, $email)) {
419 $page->trigError("L'adresse email " . $email . ' est erronée.');
420 $error = true;
421 }
422 }
423 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
424 $page->trigError("Indique au moins un destinataire.");
425 $error = true;
426 }
427
428 if ($error) {
429 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
430 } else {
431 $mymail = new PlMailer();
432 $mymail->setFrom($from);
433 $mymail->setSubject($subj);
434 if (!empty($to)) { $mymail->addTo($to); }
435 if (!empty($cc)) { $mymail->addCc($cc); }
436 if (!empty($bcc)) { $mymail->addBcc($bcc); }
437 if (!empty($to2)) { $mymail->addTo($to2); }
438 if (!empty($cc2)) { $mymail->addCc($cc2); }
439 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
440 foreach ($files as $name=>&$upload) {
441 $mymail->addUploadAttachment($upload, $name);
442 }
443 if (Env::v('nowiki')) {
444 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
445 } else {
446 $mymail->setWikiBody($txt);
447 }
448 if ($mymail->send()) {
449 $page->trigSuccess("Ton email a bien été envoyé.");
450 $_REQUEST = array('bcc' => S::user()->bestEmail());
451 PlUpload::clear(S::user()->login(), 'emails.send');
452 } else {
453 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
454 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
455 }
456 }
457 }
458 } else {
459 $res = XDB::query("SELECT data
460 FROM email_send_save
461 WHERE uid = {?}", S::i('uid'));
462 if ($res->numRows() == 0) {
463 PlUpload::clear(S::user()->login(), 'emails.send');
464 $_REQUEST['bcc'] = S::user()->bestEmail();
465 } else {
466 $data = unserialize($res->fetchOneCell());
467 $_REQUEST = array_merge($_REQUEST, $data);
468 }
469 }
470
471 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
472 new UFC_Registered()),
473 UserFilter::sortByName());
474 $contacts = $uf->getProfiles();
475 $page->assign('contacts', $contacts);
476 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
477 $page->assign('user', S::user());
478 }
479
480 function handler_test($page, $hruid = null)
481 {
482 require_once 'emails.inc.php';
483
484 if (!S::has_xsrf_token()) {
485 return PL_FORBIDDEN;
486 }
487
488 // Retrieves the User object for the test email recipient.
489 if (S::admin() && $hruid) {
490 $user = User::getSilent($hruid);
491 } else {
492 $user = S::user();
493 }
494 if (!$user) {
495 return PL_NOT_FOUND;
496 }
497
498 // Sends the test email.
499 $redirect = new Redirect($user);
500
501 $mailer = new PlMailer('emails/test.mail.tpl');
502 $mailer->assign('email', $user->bestEmail());
503 $mailer->assign('redirects', $redirect->active_emails());
504 $mailer->assign('display_name', $user->displayName());
505 $mailer->assign('sexe', $user->isFemale());
506 $mailer->send($user->isEmailFormatHtml());
507 exit;
508 }
509
510 function handler_rewrite_in($page, $mail, $hash)
511 {
512 $page->changeTpl('emails/rewrite.tpl');
513 $page->assign('option', 'in');
514 if (empty($mail) || empty($hash)) {
515 return PL_NOT_FOUND;
516 }
517 $pos = strrpos($mail, '_');
518 if ($pos === false) {
519 return PL_NOT_FOUND;
520 }
521 $mail{$pos} = '@';
522 $res = XDB::query('SELECT COUNT(*)
523 FROM email_redirect_account
524 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
525 $mail, $hash);
526 $count = intval($res->fetchOneCell());
527 if ($count > 0) {
528 XDB::query('UPDATE email_redirect_account
529 SET allow_rewrite = true, hash = NULL
530 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
531 $mail, $hash);
532 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
533 return;
534 }
535 return PL_NOT_FOUND;
536 }
537
538 function handler_rewrite_out($page, $mail, $hash)
539 {
540 $page->changeTpl('emails/rewrite.tpl');
541 $page->assign('option', 'out');
542 if (empty($mail) || empty($hash)) {
543 return PL_NOT_FOUND;
544 }
545 $pos = strrpos($mail, '_');
546 if ($pos === false) {
547 return PL_NOT_FOUND;
548 }
549 $mail{$pos} = '@';
550 $res = XDB::query('SELECT COUNT(*)
551 FROM email_redirect_account
552 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
553 $mail, $hash);
554 $count = intval($res->fetchOneCell());
555 if ($count > 0) {
556 global $globals;
557 $res = XDB::query('SELECT e.redirect, e.rewrite, a.hruid
558 FROM email_redirect_account AS e
559 INNER JOIN accounts AS a ON (e.uid = a.uid)
560 WHERE e.redirect = {?} AND e.hash = {?}',
561 $mail, $hash);
562 XDB::query('UPDATE email_redirect_account
563 SET allow_rewrite = false, hash = NULL
564 WHERE redirect = {?} AND hash = {?}',
565 $mail, $hash);
566 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
567 $mail = new PlMailer();
568 $mail->setFrom("webmaster@" . $globals->mail->domain);
569 $mail->addTo("support@" . $globals->mail->domain);
570 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
571 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
572 $mail->send();
573 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
574 return;
575 }
576 return PL_NOT_FOUND;
577 }
578
579 function handler_imap_in($page, $hash = null, $login = null)
580 {
581 $page->changeTpl('emails/imap_register.tpl');
582 $user = null;
583 if (!empty($hash) || !empty($login)) {
584 $user = User::getSilent($login);
585 if ($user) {
586 $req = XDB::query('SELECT 1
587 FROM newsletter_ins
588 WHERE uid = {?} AND hash = {?}',
589 $user->id(), $hash);
590 if ($req->numRows() == 0) {
591 $user = null;
592 }
593 }
594 }
595
596 require_once 'emails.inc.php';
597 $page->assign('ok', false);
598 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
599 Email::activate_storage(S::user(), 'imap');
600 $page->assign('ok', true);
601 $page->assign('yourself', S::user()->displayName());
602 $page->assign('sexe', S::user()->isFemale());
603 } else if (!S::logged() && $user) {
604 Email::activate_storage($user, 'imap');
605 $page->assign('ok', true);
606 $page->assign('yourself', $user->displayName());
607 $page->assign('sexe', $user->isFemale());
608 }
609 }
610
611 function handler_broken($page, $warn = null, $email = null)
612 {
613 require_once 'emails.inc.php';
614 $wp = new PlWikiPage('Xorg.PatteCassée');
615 $wp->buildCache();
616
617 global $globals;
618
619 $page->changeTpl('emails/broken.tpl');
620
621 if ($warn == 'warn' && $email) {
622 S::assert_xsrf_token();
623
624 $email = valide_email($email);
625 // vérifications d'usage
626 $uid = XDB::fetchOneCell("SELECT uid
627 FROM emails
628 WHERE email = {?}", $email);
629 if ($uid) {
630 $dest = User::getWithUID($uid);
631
632 $mail = new PlMailer('emails/broken-web.mail.tpl');
633 $mail->assign('email', $email);
634 $mail->assign('request', S::user());
635 $mail->sendTo($dest);
636 $page->trigSuccess('Email envoyé&nbsp;!');
637 }
638 } elseif (Post::has('email')) {
639 S::assert_xsrf_token();
640
641 $email = valide_email(Post::v('email'));
642
643 list(,$fqdn) = explode('@', $email);
644 $fqdn = strtolower($fqdn);
645 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
646 $page->assign('neuneu', true);
647 } else {
648 $page->assign('email',$email);
649 $x = XDB::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne, a.hruid,
650 (COUNT(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
651 FROM emails AS e1
652 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
653 INNER JOIN accounts AS a ON (e1.uid = a.uid)
654 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid
655 AND FIND_IN_SET('active', e2.flags)
656 AND e1.email != e2.email)
657 WHERE e1.email = {?}
658 GROUP BY e1.uid", $email);
659 if ($x) {
660 // on écrit dans la base que l'adresse est cassée
661 if (!$x['panne']) {
662 XDB::execute("UPDATE emails
663 SET panne=NOW(), last=NOW(), panne_level = 1
664 WHERE email = {?}", $email);
665 } else {
666 XDB::execute("UPDATE emails
667 SET panne_level = 1
668 WHERE email = {?} AND panne_level = 0", $email);
669 }
670 $x['user'] = User::getWithUID($x['uid']);
671 $page->assign_by_ref('x', $x);
672 }
673 }
674 }
675 }
676
677 function handler_duplicated($page, $action = 'list', $email = null)
678 {
679 $page->changeTpl('emails/duplicated.tpl');
680
681 $states = array('pending' => 'En attente...',
682 'safe' => 'Pas d\'inquiétude',
683 'unsafe' => 'Recherches en cours',
684 'dangerous' => 'Usurpations par cette adresse');
685 $page->assign('states', $states);
686
687 if (Post::has('action')) {
688 S::assert_xsrf_token();
689 }
690 switch (Post::v('action')) {
691 case 'create':
692 if (trim(Post::v('emailN')) != '') {
693 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
694 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
695 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
696 };
697 break;
698
699 case 'edit':
700 Xdb::execute('UPDATE email_watch
701 SET state = {?}, last = NOW(), uid = {?}, description = {?}
702 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
703 break;
704
705 default:
706 if ($action == 'delete' && !is_null($email)) {
707 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
708 }
709 }
710 if ($action != 'create' && $action != 'edit') {
711 $action = 'list';
712 }
713 $page->assign('action', $action);
714
715 if ($action == 'list') {
716 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
717 FROM email_watch AS w
718 LEFT JOIN emails AS e USING(email)
719 LEFT JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
720 ORDER BY w.state, w.email, a.alias";
721 $it = Xdb::iterRow($sql);
722
723 $table = array();
724 $props = array();
725 while (list($email, $date, $state, $forlife) = $it->next()) {
726 if (count($props) == 0 || $props['mail'] != $email) {
727 if (count($props) > 0) {
728 $table[] = $props;
729 }
730 $props = array('mail' => $email,
731 'detection' => $date,
732 'state' => $state,
733 'users' => array($forlife));
734 } else {
735 $props['users'][] = $forlife;
736 }
737 }
738 if (count($props) > 0) {
739 $table[] = $props;
740 }
741 $page->assign('table', $table);
742 } elseif ($action == 'edit') {
743 $sql = "SELECT w.detection, w.state, w.last, w.description,
744 a1.alias AS edit, a2.alias AS forlife
745 FROM email_watch AS w
746 LEFT JOIN aliases AS a1 ON (a1.uid = w.uid AND a1.type = 'a_vie')
747 LEFT JOIN emails AS e ON (w.email = e.email)
748 LEFT JOIN aliases AS a2 ON (a2.uid = e.uid AND a2.type = 'a_vie')
749 WHERE w.email = {?}
750 ORDER BY a2.alias";
751 $it = Xdb::iterRow($sql, $email);
752
753 $props = array();
754 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
755 if (count($props) == 0) {
756 $props = array('mail' => $email,
757 'detection' => $detection,
758 'state' => $state,
759 'last' => $last,
760 'description' => $description,
761 'edit' => $edit,
762 'users' => array($forlife));
763 } else {
764 $props['users'][] = $forlife;
765 }
766 }
767 $page->assign('doublon', $props);
768 }
769 }
770
771 function handler_lost($page, $action = 'list', $email = null)
772 {
773 $page->changeTpl('emails/lost.tpl');
774
775 $page->assign('lost_emails',
776 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
777 FROM accounts AS a
778 INNER JOIN email_options AS eo ON (eo.uid = a.uid)
779 LEFT JOIN emails AS e ON (a.uid = e.uid AND FIND_IN_SET(\'active\', e.flags))
780 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', perms))
781 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
782 WHERE e.uid IS NULL AND FIND_IN_SET(\'googleapps\', eo.storage) = 0
783 AND a.state = \'active\'
784 ORDER BY pd.promo, a.hruid'));
785 }
786
787 function handler_broken_addr($page)
788 {
789 require_once 'emails.inc.php';
790 $page->changeTpl('emails/broken_addr.tpl');
791
792 if (Env::has('sort_broken')) {
793 S::assert_xsrf_token();
794
795 $list = trim(Env::v('list'));
796 if ($list == '') {
797 $page->trigError('La liste est vide.');
798 } else {
799 $valid_emails = array();
800 $invalid_emails = array();
801 $broken_list = explode("\n", $list);
802 sort($broken_list);
803 foreach ($broken_list as $orig_email) {
804 $orig_email = trim($orig_email);
805 if ($orig_email != '') {
806 $email = valide_email($orig_email);
807 if (empty($email) || $email == '@') {
808 $invalid_emails[] = trim($orig_email) . ': invalid email';
809 } elseif (!in_array($email, $valid_emails)) {
810 $res = XDB::query('SELECT COUNT(*)
811 FROM emails
812 WHERE email = {?}', $email);
813 if ($res->fetchOneCell() > 0) {
814 $valid_emails[] = $email;
815 } else {
816 $invalid_emails[] = "$orig_email: no such redirection";
817 }
818 }
819 }
820 }
821
822 $page->assign('valid_emails', $valid_emails);
823 $page->assign('invalid_emails', $invalid_emails);
824 }
825 }
826
827 if (Env::has('process_broken')) {
828 S::assert_xsrf_token();
829
830 $list = trim(Env::v('list'));
831 if ($list == '') {
832 $page->trigError('La liste est vide.');
833 } else {
834 $broken_user_list = array();
835 $broken_list = explode("\n", $list);
836 sort($broken_list);
837 foreach ($broken_list as $orig_email) {
838 $email = valide_email(trim($orig_email));
839 if (empty($email) || $email == '@') {
840 continue;
841 }
842
843 $sel = XDB::query(
844 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
845 acc.full_name, a.alias
846 FROM emails AS e1
847 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
848 AND e1.email != e2.email)
849 INNER JOIN accounts AS acc ON (e1.uid = acc.uid)
850 INNER JOIN aliases AS a ON (acc.uid = a.uid AND FIND_IN_SET('bestalias', a.flags))
851 WHERE e1.email = {?}
852 GROUP BY e1.uid", $email);
853
854 if ($x = $sel->fetchOneAssoc()) {
855 if (!$x['panne']) {
856 XDB::execute('UPDATE emails
857 SET panne=NOW(), last=NOW(), panne_level = 1
858 WHERE email = {?}',
859 $email);
860 } else {
861 XDB::execute('UPDATE emails
862 SET last = CURDATE(), panne_level = panne_level + 1
863 WHERE email = {?}
864 AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
865 $email);
866 }
867
868 if (!empty($x['nb_mails'])) {
869 $mail = new PlMailer('emails/broken.mail.tpl');
870 $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
871 . Platal::globals()->mail->domain . '>');
872 $mail->assign('x', $x);
873 $mail->assign('email', $email);
874 $mail->send();
875 }
876
877 if (!isset($broken_user_list[$x['alias']])) {
878 $broken_user_list[$x['alias']] = array($email);
879 } else {
880 $broken_user_list[$x['alias']][] = $email;
881 }
882 }
883 }
884
885 XDB::execute("UPDATE emails
886 SET panne_level = panne_level - 1
887 WHERE flags = 'active' AND panne_level > 1
888 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
889 XDB::execute("UPDATE emails
890 SET panne_level = 0
891 WHERE flags = 'active' AND panne_level = 1
892 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
893
894 // Output the list of users with recently broken addresses,
895 // along with the count of valid redirections.
896 require_once 'notifs.inc.php';
897 pl_cached_content_headers('text/x-csv', 1);
898
899 $csv = fopen('php://output', 'w');
900 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
901 foreach ($broken_user_list as $alias => $mails) {
902 $sel = Xdb::query(
903 "SELECT acc.uid, count(DISTINCT(e.email)) AS nb_mails,
904 IFNULL(pd.public_name, acc.full_name) AS fullname,
905 IFNULL(pd.promo, 0) AS promo, IFNULL(pce.name, 'Aucun') AS corps,
906 IFNULL(pje.name, 'Aucun') AS job, GROUP_CONCAT(pn.address SEPARATOR ', ') AS networking
907 FROM aliases AS a
908 INNER JOIN accounts AS acc ON (a.uid = acc.uid)
909 LEFT JOIN emails AS e ON (e.uid = acc.uid
910 AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
911 LEFT JOIN account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
912 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
913 LEFT JOIN profile_corps AS pc ON (pc.pid = ap.pid)
914 LEFT JOIN profile_corps_enum AS pce ON (pc.current_corpsid = pce.id)
915 LEFT JOIN profile_job AS pj ON (pj.pid = ap.pid)
916 LEFT JOIN profile_job_enum AS pje ON (pj.jobid = pje.id)
917 LEFT JOIN profile_networking AS pn ON (pn.pid = ap.pid)
918 WHERE a.alias = {?}
919 GROUP BY acc.uid", $alias);
920
921 if ($x = $sel->fetchOneAssoc()) {
922 if ($x['nb_mails'] == 0) {
923 $user = User::getSilentWithUID($x['uid']);
924 $profile = $user->profile();
925 WatchProfileUpdate::register($profile, 'broken');
926 }
927 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
928 join(',', $mails), $x['nb_mails'],
929 'https://www.polytechnique.org/marketing/broken/' . $alias,
930 $x['corps'], $x['job'], $x['networking']), ';');
931 }
932 }
933 fclose($csv);
934 exit;
935 }
936 }
937 }
938 }
939
940 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
941 ?>