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