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