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