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