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