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