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