Previous fix was not good.
[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 $page->assign('best_email', $user->bestEmail());
302
303 $page->assign('emails', $redirect->emails);
304
305 // Display GoogleApps acount information.
306 require_once 'googleapps.inc.php';
307 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
308
309 require_once 'emails.combobox.inc.php';
310 fill_email_combobox($page);
311 }
312
313 function handler_antispam($page, $filter_status = null, $redirection = null)
314 {
315 require_once 'emails.inc.php';
316 $wp = new PlWikiPage('Xorg.Antispam');
317 $wp->buildCache();
318
319 $page->changeTpl('emails/antispam.tpl');
320
321 $user = S::user();
322 $bogo = new Bogo($user);
323 if (!is_null($filter_status)) {
324 if (is_null($redirection)) {
325 $bogo->changeAll($filter_status);
326 } else {
327 $bogo->change($redirection, $filter_status);
328 }
329 }
330 $page->assign('filter', $bogo->state);
331 $page->assign('single_state', $bogo->single_state);
332 $page->assign('single_redirection', $bogo->single_redirection);
333 $page->assign('redirections', $bogo->redirections);
334 }
335
336 function handler_submit($page)
337 {
338 $wp = new PlWikiPage('Xorg.Mails');
339 $wp->buildCache();
340 $page->changeTpl('emails/submit_spam.tpl');
341
342 if (Post::has('send_email')) {
343 S::assert_xsrf_token();
344
345 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
346 if (!$upload) {
347 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
348 return;
349 }
350 $mime = $upload->contentType();
351 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
352 $upload->clear();
353 $page->trigError('Le fichier ne contient pas un email complet');
354 return;
355 }
356 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
357
358 global $globals;
359 $box = $type . '@' . $globals->mail->domain;
360 $mailer = new PlMailer();
361 $mailer->addTo($box);
362 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
363 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
364 $mailer->addUploadAttachment($upload, $type . '.mail');
365 $mailer->send();
366 $page->trigSuccess('Le message a été transmis à ' . $box);
367 $upload->clear();
368 }
369 }
370
371 function handler_send($page)
372 {
373 $page->changeTpl('emails/send.tpl');
374
375 $page->setTitle('Envoyer un email');
376
377 // action si on recoit un formulaire
378 if (Post::has('save')) {
379 if (!S::has_xsrf_token()) {
380 return PL_FORBIDDEN;
381 }
382
383 unset($_POST['save']);
384 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
385 Post::set('to_contacts', explode(';', Post::s('to_contacts')));
386 Post::set('cc_contacts', explode(';', Post::s('cc_contacts')));
387 $data = serialize($_POST);
388 XDB::execute('INSERT INTO email_send_save (uid, data)
389 VALUES ({?}, {?})
390 ON DUPLICATE KEY UPDATE data = VALUES(data)',
391 S::user()->id('uid'), $data);
392 }
393 exit;
394 } else if (Env::v('submit') == 'Envoyer') {
395 S::assert_xsrf_token();
396
397 function getEmails($aliases)
398 {
399 if (!is_array($aliases)) {
400 return null;
401 }
402 $uf = new UserFilter(new UFC_Hrpid($aliases));
403 $users = $uf->iterUsers();
404 $ret = array();
405 while ($user = $users->next()) {
406 $ret[] = $user->forlife;
407 }
408 return join(', ', $ret);
409 }
410
411 $error = false;
412 foreach ($_FILES as &$file) {
413 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
414 $page->trigError(PlUpload::$lastError);
415 $error = true;
416 break;
417 }
418 }
419
420 if (!$error) {
421 XDB::execute("DELETE FROM email_send_save
422 WHERE uid = {?}",
423 S::user()->id());
424
425 $to2 = getEmails(Env::v('to_contacts'));
426 $cc2 = getEmails(Env::v('cc_contacts'));
427 $txt = str_replace('^M', '', Env::v('contenu'));
428 $to = str_replace(';', ',', Env::t('to'));
429 $subj = Env::t('sujet');
430 $from = Env::t('from');
431 $cc = str_replace(';', ',', Env::t('cc'));
432 $bcc = str_replace(';', ',', Env::t('bcc'));
433
434 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
435 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
436 $email = trim($email);
437 if ($email != '' && !preg_match($email_regex, $email)) {
438 $page->trigError("L'adresse email " . $email . ' est erronée.');
439 $error = true;
440 }
441 }
442 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
443 $page->trigError("Indique au moins un destinataire.");
444 $error = true;
445 }
446
447 if ($error) {
448 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
449 } else {
450 $mymail = new PlMailer();
451 $mymail->setFrom($from);
452 $mymail->setSubject($subj);
453 if (!empty($to)) { $mymail->addTo($to); }
454 if (!empty($cc)) { $mymail->addCc($cc); }
455 if (!empty($bcc)) { $mymail->addBcc($bcc); }
456 if (!empty($to2)) { $mymail->addTo($to2); }
457 if (!empty($cc2)) { $mymail->addCc($cc2); }
458 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
459 foreach ($files as $name=>&$upload) {
460 $mymail->addUploadAttachment($upload, $name);
461 }
462 if (Env::v('nowiki')) {
463 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
464 } else {
465 $mymail->setWikiBody($txt);
466 }
467 if ($mymail->send()) {
468 $page->trigSuccess("Ton email a bien été envoyé.");
469 $_REQUEST = array('bcc' => S::user()->bestEmail());
470 PlUpload::clear(S::user()->login(), 'emails.send');
471 } else {
472 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
473 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
474 }
475 }
476 }
477 } else {
478 $res = XDB::query("SELECT data
479 FROM email_send_save
480 WHERE uid = {?}", S::i('uid'));
481 if ($res->numRows() == 0) {
482 PlUpload::clear(S::user()->login(), 'emails.send');
483 $_REQUEST['bcc'] = S::user()->bestEmail();
484 } else {
485 $data = unserialize($res->fetchOneCell());
486 $_REQUEST = array_merge($_REQUEST, $data);
487 }
488 }
489
490 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
491 new UFC_Registered()),
492 UserFilter::sortByName());
493 $contacts = $uf->getProfiles();
494 $page->assign('contacts', $contacts);
495 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
496 $page->assign('user', S::user());
497 }
498
499 function handler_test($page, $hruid = null)
500 {
501 require_once 'emails.inc.php';
502
503 if (!S::has_xsrf_token()) {
504 return PL_FORBIDDEN;
505 }
506
507 // Retrieves the User object for the test email recipient.
508 if (S::admin() && $hruid) {
509 $user = User::getSilent($hruid);
510 } else {
511 $user = S::user();
512 }
513 if (!$user) {
514 return PL_NOT_FOUND;
515 }
516
517 // Sends the test email.
518 $redirect = new Redirect($user);
519
520 $mailer = new PlMailer('emails/test.mail.tpl');
521 $mailer->assign('email', $user->bestEmail());
522 $mailer->assign('redirects', $redirect->active_emails());
523 $mailer->assign('display_name', $user->displayName());
524 $mailer->assign('sexe', $user->isFemale());
525 $mailer->send($user->isEmailFormatHtml());
526 exit;
527 }
528
529 function handler_rewrite_in($page, $mail, $hash)
530 {
531 $page->changeTpl('emails/rewrite.tpl');
532 $page->assign('option', 'in');
533 if (empty($mail) || empty($hash)) {
534 return PL_NOT_FOUND;
535 }
536 $pos = strrpos($mail, '_');
537 if ($pos === false) {
538 return PL_NOT_FOUND;
539 }
540 $mail{$pos} = '@';
541 $res = XDB::query('SELECT COUNT(*)
542 FROM email_redirect_account
543 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
544 $mail, $hash);
545 $count = intval($res->fetchOneCell());
546 if ($count > 0) {
547 XDB::query('UPDATE email_redirect_account
548 SET allow_rewrite = true, hash = NULL
549 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
550 $mail, $hash);
551 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
552 return;
553 }
554 return PL_NOT_FOUND;
555 }
556
557 function handler_rewrite_out($page, $mail, $hash)
558 {
559 $page->changeTpl('emails/rewrite.tpl');
560 $page->assign('option', 'out');
561 if (empty($mail) || empty($hash)) {
562 return PL_NOT_FOUND;
563 }
564 $pos = strrpos($mail, '_');
565 if ($pos === false) {
566 return PL_NOT_FOUND;
567 }
568 $mail{$pos} = '@';
569 $res = XDB::query('SELECT COUNT(*)
570 FROM email_redirect_account
571 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
572 $mail, $hash);
573 $count = intval($res->fetchOneCell());
574 if ($count > 0) {
575 global $globals;
576 $res = XDB::query('SELECT e.redirect, e.rewrite, a.hruid
577 FROM email_redirect_account AS e
578 INNER JOIN accounts AS a ON (e.uid = a.uid)
579 WHERE e.redirect = {?} AND e.hash = {?}',
580 $mail, $hash);
581 XDB::query('UPDATE email_redirect_account
582 SET allow_rewrite = false, hash = NULL
583 WHERE redirect = {?} AND hash = {?}',
584 $mail, $hash);
585 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
586 $mail = new PlMailer();
587 $mail->setFrom("webmaster@" . $globals->mail->domain);
588 $mail->addTo("support@" . $globals->mail->domain);
589 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
590 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
591 $mail->send();
592 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
593 return;
594 }
595 return PL_NOT_FOUND;
596 }
597
598 function handler_imap_in($page, $hash = null, $login = null)
599 {
600 $page->changeTpl('emails/imap_register.tpl');
601 $user = null;
602 if (!empty($hash) || !empty($login)) {
603 $user = User::getSilent($login);
604 if ($user) {
605 $req = XDB::query('SELECT 1
606 FROM newsletter_ins
607 WHERE uid = {?} AND hash = {?}',
608 $user->id(), $hash);
609 if ($req->numRows() == 0) {
610 $user = null;
611 }
612 }
613 }
614
615 require_once 'emails.inc.php';
616 $page->assign('ok', false);
617 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
618 Email::activate_storage(S::user(), 'imap');
619 $page->assign('ok', true);
620 $page->assign('yourself', S::user()->displayName());
621 $page->assign('sexe', S::user()->isFemale());
622 } else if (!S::logged() && $user) {
623 Email::activate_storage($user, 'imap');
624 $page->assign('ok', true);
625 $page->assign('yourself', $user->displayName());
626 $page->assign('sexe', $user->isFemale());
627 }
628 }
629
630 function handler_broken($page, $warn = null, $email = null)
631 {
632 require_once 'emails.inc.php';
633 $wp = new PlWikiPage('Xorg.PatteCassée');
634 $wp->buildCache();
635
636 global $globals;
637
638 $page->changeTpl('emails/broken.tpl');
639
640 if ($warn == 'warn' && $email) {
641 S::assert_xsrf_token();
642
643 // Usual verifications.
644 $email = valide_email($email);
645 $uid = XDB::fetchOneCell('SELECT uid
646 FROM email_redirect_account
647 WHERE redirect = {?}', $email);
648
649 if ($uid) {
650 $dest = User::getWithUID($uid);
651
652 $mail = new PlMailer('emails/broken-web.mail.tpl');
653 $mail->assign('email', $email);
654 $mail->assign('request', S::user());
655 $mail->sendTo($dest);
656 $page->trigSuccess('Email envoyé&nbsp;!');
657 }
658 } elseif (Post::has('email')) {
659 S::assert_xsrf_token();
660
661 $email = Post::t('email');
662
663 if (!User::isForeignEmailAddress($email)) {
664 $page->assign('neuneu', true);
665 } else {
666 $user = mark_broken_email($email);
667 $page->assign('user', $user);
668 $page->assign('email', $email);
669 }
670 }
671 }
672
673 function handler_duplicated($page, $action = 'list', $email = null)
674 {
675 $page->changeTpl('emails/duplicated.tpl');
676
677 $states = array('pending' => 'En attente...',
678 'safe' => 'Pas d\'inquiétude',
679 'unsafe' => 'Recherches en cours',
680 'dangerous' => 'Usurpations par cette adresse');
681 $page->assign('states', $states);
682
683 if (Post::has('action')) {
684 S::assert_xsrf_token();
685 }
686 switch (Post::v('action')) {
687 case 'create':
688 if (trim(Post::v('emailN')) != '') {
689 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
690 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
691 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
692 };
693 break;
694
695 case 'edit':
696 Xdb::execute('UPDATE email_watch
697 SET state = {?}, last = NOW(), uid = {?}, description = {?}
698 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
699 break;
700
701 default:
702 if ($action == 'delete' && !is_null($email)) {
703 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
704 }
705 }
706 if ($action != 'create' && $action != 'edit') {
707 $action = 'list';
708 }
709 $page->assign('action', $action);
710
711 if ($action == 'list') {
712 $it = XDB::iterRow('SELECT w.email, w.detection, w.state, s.email AS forlife
713 FROM email_watch AS w
714 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
715 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
716 ORDER BY w.state, w.email, s.email');
717
718 $table = array();
719 $props = array();
720 while (list($email, $date, $state, $forlife) = $it->next()) {
721 if (count($props) == 0 || $props['mail'] != $email) {
722 if (count($props) > 0) {
723 $table[] = $props;
724 }
725 $props = array('mail' => $email,
726 'detection' => $date,
727 'state' => $state,
728 'users' => array($forlife));
729 } else {
730 $props['users'][] = $forlife;
731 }
732 }
733 if (count($props) > 0) {
734 $table[] = $props;
735 }
736 $page->assign('table', $table);
737 } elseif ($action == 'edit') {
738 $it = XDB::iterRow('SELECT w.detection, w.state, w.last, w.description,
739 a.hruid AS edit, s.email AS forlife
740 FROM email_watch AS w
741 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
742 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
743 LEFT JOIN accounts AS a ON (w.uid = a.uid)
744 WHERE w.email = {?}
745 ORDER BY s.email',
746 $email);
747
748 $props = array();
749 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
750 if (count($props) == 0) {
751 $props = array('mail' => $email,
752 'detection' => $detection,
753 'state' => $state,
754 'last' => $last,
755 'description' => $description,
756 'edit' => $edit,
757 'users' => array($forlife));
758 } else {
759 $props['users'][] = $forlife;
760 }
761 }
762 $page->assign('doublon', $props);
763 }
764 }
765
766 function handler_lost($page, $action = 'list', $email = null)
767 {
768 $page->changeTpl('emails/lost.tpl');
769
770 $page->assign('lost_emails',
771 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
772 FROM accounts AS a
773 INNER JOIN account_types AS at ON (a.type = at.type)
774 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
775 AND er.type != \'imap\' AND er.type != \'homonym\')
776 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
777 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
778 WHERE a.state = \'active\' AND er.redirect IS NULL AND FIND_IN_SET(\'mail\', at.perms)
779 GROUP BY a.uid
780 ORDER BY pd.promo, a.hruid'));
781 }
782
783 function handler_broken_addr($page)
784 {
785 require_once 'emails.inc.php';
786 $page->changeTpl('emails/broken_addr.tpl');
787
788 if (Env::has('sort_broken')) {
789 S::assert_xsrf_token();
790
791 $list = trim(Env::v('list'));
792 if ($list == '') {
793 $page->trigError('La liste est vide.');
794 } else {
795 $valid_emails = array();
796 $invalid_emails = array();
797 $broken_list = explode("\n", $list);
798 sort($broken_list);
799 foreach ($broken_list as $orig_email) {
800 $orig_email = trim($orig_email);
801 if ($orig_email != '') {
802 $email = valide_email($orig_email);
803 if (empty($email) || $email == '@') {
804 $invalid_emails[] = trim($orig_email) . ': invalid email';
805 } elseif (!in_array($email, $valid_emails)) {
806 $nb = XDB::fetchOneCell('SELECT COUNT(*)
807 FROM email_redirect_account
808 WHERE redirect = {?}', $email);
809 if ($nb > 0) {
810 $valid_emails[] = $email;
811 } else {
812 $invalid_emails[] = $orig_email . ': no such redirection';
813 }
814 }
815 }
816 }
817
818 $page->assign('valid_emails', $valid_emails);
819 $page->assign('invalid_emails', $invalid_emails);
820 }
821 }
822
823 if (Env::has('process_broken')) {
824 S::assert_xsrf_token();
825
826 $list = trim(Env::v('list'));
827 if ($list == '') {
828 $page->trigError('La liste est vide.');
829 } else {
830 require_once 'notifs.inc.php';
831
832 $broken_user_list = array();
833 $broken_user_email_count = array();
834 $broken_list = explode("\n", $list);
835 sort($broken_list);
836
837 foreach ($broken_list as $email) {
838 if ($user = mark_broken_email($email, true)) {
839 if ($user['nb_mails'] > 0 && $user['notify']) {
840 $mail = new PlMailer('emails/broken.mail.tpl');
841 $dest = User::getSilentWithUID($user['uid']);
842 $mail->setTo($dest);
843 $mail->assign('user', $user);
844 $mail->assign('email', $email);
845 $mail->send();
846 } else {
847 $profile = Profile::get($user['alias']);
848 WatchProfileUpdate::register($profile, 'broken');
849 }
850
851 if (!isset($broken_user_list[$user['uid']])) {
852 $broken_user_list[$user['uid']] = array($email);
853 } else {
854 $broken_user_list[$user['uid']][] = $email;
855 }
856 $broken_user_email_count[$user['uid']] = $user['nb_mails'];
857 }
858 }
859
860 XDB::execute('UPDATE email_redirect_account
861 SET broken_level = broken_level - 1
862 WHERE flags = \'active\' AND broken_level > 1
863 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()');
864 XDB::execute('UPDATE email_redirect_account
865 SET broken_level = 0
866 WHERE flags = \'active\' AND broken_level = 1
867 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()');
868
869 // Output the list of users with recently broken addresses,
870 // along with the count of valid redirections.
871 pl_cached_content_headers('text/x-csv', 1);
872
873 $csv = fopen('php://output', 'w');
874 fputcsv($csv, array('nom', 'promo', 'bounces', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
875 foreach ($broken_user_list as $uid => $mails) {
876 $profile = Profile::get($uid);
877 $corps = $profile->getCorps();
878 $current_corps = ($corps && $corps->current) ? $corps->current : '';
879 $jobs = $profile->getJobs();
880 $companies = array();
881 foreach ($jobs as $job) {
882 $companies[] = $job->company->name;
883 }
884 $networkings = $profile->getNetworking(Profile::NETWORKING_ALL);
885 $networking_list = array();
886 foreach ($networkings as $networking) {
887 $networking_list[] = $networking['address'];
888 }
889 fputcsv($csv, array($profile->fullName(), $profile->promo(),
890 join(',', $mails), $broken_user_email_count[$uid],
891 'https://www.polytechnique.org/marketing/broken/' . $profile->hrid(),
892 $current_corps, implode(',', $companies), implode(',', $networking_list)), ';');
893 }
894 fclose($csv);
895 exit;
896 }
897 }
898 }
899 }
900
901 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
902 ?>