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