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