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