Merge branch 'xorg/maint' into xorg/master
[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 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'),
44 'admin/emails/broken' => $this->make_hook('broken_addr', AUTH_PASSWD, '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);
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
SJ
100 WHERE s.uid = {?}
101 ORDER BY !alias, s.email",
08d33afc 102 $user->id());
b4503762
SJ
103 $page->assign('aliases', $aliases);
104
08d33afc
SJ
105 $alias = XDB::fetchOneCell('SELECT COUNT(email)
106 FROM email_source_account
107 WHERE uid = {?} AND type = \'alias_aux\'',
108 $user->id());
b4503762
SJ
109 $page->assign('alias', $alias);
110
81b5b746 111
2d997414 112 // Check for homonyms.
777c5910 113 $page->assign('homonyme', $user->homonyme);
e1547442 114
2d997414
VZ
115 // Display active redirections.
116 $redirect = new Redirect($user);
e97e9b8f 117 $page->assign('mails', $redirect->active_emails());
f036c896
SJ
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);
81b5b746 125 }
126
26ba053e 127 function handler_alias($page, $action = null, $value = null)
81b5b746 128 {
81b5b746 129 global $globals;
130
131 $page->changeTpl('emails/alias.tpl');
46f272fe 132 $page->setTitle('Alias melix.net');
81b5b746 133
2d997414 134 $user = S::user();
b4503762 135 $page->assign('request', AliasReq::get_request($user->id()));
81b5b746 136
2d997414 137 // Remove the email alias.
b4503762 138 if ($action == 'delete') {
40d428d8
VZ
139 S::assert_xsrf_token();
140
08d33afc
SJ
141 XDB::execute('DELETE FROM email_source_account
142 WHERE uid = {?} AND type = \'alias_aux\'',
143 $user->id());
b4503762
SJ
144
145 require_once 'emails.inc.php';
146 fix_bestalias($user);
81b5b746 147 }
148
08d33afc 149 // Fetch existing auxiliary aliases.
b4503762
SJ
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)
08d33afc
SJ
153 WHERE s.uid = {?} AND s.type = \'alias_aux\'',
154 $user->id());
b4503762
SJ
155 $visibility = $user->hasProfile() && ($user->profile(true)->alias_pub == 'public');
156 $page->assign('current', $alias);
5b6768e6
FB
157 $page->assign('user', $user);
158 $page->assign('mail_public', $visibility);
81b5b746 159
b4503762 160 if ($action == 'ask' && Env::has('alias') && Env::has('reason')) {
40d428d8 161 S::assert_xsrf_token();
81b5b746 162
b4503762
SJ
163 // Retrieves user request.
164 $new_alias = Env::v('alias');
165 $reason = Env::v('reason');
6a4f0f01 166 $public = (Env::v('public', 'off') == 'on') ? 'public' : 'private';
81b5b746 167
b4503762
SJ
168 $page->assign('r_alias', $new_alias);
169 $page->assign('r_reason', $reason);
81b5b746 170 if ($public == 'public') {
171 $page->assign('r_public', true);
172 }
173
b4503762
SJ
174 // Checks special charaters in alias.
175 if (!preg_match("/^[a-zA-Z0-9\-.]{3,20}$/", $new_alias)) {
a7d35093
FB
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 .");
fd8f77de 180 return;
81b5b746 181 } else {
b4503762 182 // Checks if the alias has already been given.
08d33afc
SJ
183 $res = XDB::query('SELECT COUNT(email)
184 FROM email_source_account
185 WHERE email = {?} AND type = \'alias_aux\'',
186 $new_alias);
81b5b746 187 if ($res->fetchOneCell() > 0) {
b4503762 188 $page->trigError("L'alias $new_alias a déja été attribué. Tu ne peux donc pas l'obtenir.");
fd8f77de 189 return;
81b5b746 190 }
191
b4503762 192 // Checks if the alias has already been asked for.
7b094a73 193 $it = Validate::iterate('alias');
81b5b746 194 while($req = $it->next()) {
b4503762
SJ
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;
81b5b746 198 }
199 }
200
b4503762
SJ
201 // Sends requests. This will erase any previous alias pending request.
202 $myalias = new AliasReq($user, $new_alias, $reason, $public, $old_alias);
81b5b746 203 $myalias->submit();
b4503762 204 $page->assign('success', $new_alias);
fd8f77de 205 return;
81b5b746 206 }
46504fb3
VZ
207 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
208 if (!S::has_xsrf_token()) {
209 return PL_FORBIDDEN;
210 }
211
3e53a496 212 if ($user->hasProfile()) {
b4503762 213 XDB::execute('UPDATE profiles
3e53a496 214 SET alias_pub = {?}
b4503762 215 WHERE pid = {?}',
3e53a496 216 $value, $user->profile()->id());
81b5b746 217 }
8446dbd3 218 exit;
81b5b746 219 }
81b5b746 220 }
221
b4503762 222 function handler_redirect($page, $action = null, $email = null, $rewrite = null)
81b5b746 223 {
224 global $globals;
81b5b746 225 require_once 'emails.inc.php';
226
227 $page->changeTpl('emails/redirect.tpl');
228
2d997414
VZ
229 $user = S::user();
230 $page->assign_by_ref('user', $user);
231 $page->assign('eleve', $user->promo() >= date("Y") - 5);
3b83212e 232
2d997414 233 $redirect = new Redirect($user);
81b5b746 234
6d6b65bf 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
2d997414 240 // Apply email redirection change requests.
1060c854 241 $result = SUCCESS;
81b5b746 242 if ($action == 'remove' && $email) {
1060c854 243 $result = $redirect->delete_email($email);
81b5b746 244 }
e1547442
FB
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) {
e1547442
FB
255 $redirect->modify_one_email_redirect($email, $rewrite);
256 }
257
40d428d8
VZ
258 if (Env::has('emailop')) {
259 S::assert_xsrf_token();
260
b4503762 261 $actifs = Env::v('emails_actifs', array());
5e2307dc 262 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
0fbd1f3f 263 $error_email = false;
b715c1e1 264 $new_email = Env::v('email');
6ea6d9c1 265 if ($new_email == "new@example.org") {
b715c1e1
SJ
266 $new_email = Env::v('email_new');
267 }
aef0283b
VZ
268 $result = $redirect->add_email($new_email);
269 if ($result == ERROR_INVALID_EMAIL) {
0fbd1f3f 270 $error_email = true;
b715c1e1
SJ
271 $page->assign('email', $new_email);
272 }
aef0283b 273 $page->assign('retour', $result);
0fbd1f3f 274 $page->assign('error_email', $error_email);
81b5b746 275 } elseif (empty($actifs)) {
1060c854 276 $result = ERROR_INACTIVE_REDIRECTION;
81b5b746 277 } elseif (is_array($actifs)) {
b4503762 278 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', array()));
81b5b746 279 }
280 }
281
1060c854 282 switch ($result) {
44b071c2
SJ
283 case ERROR_INACTIVE_REDIRECTION:
284 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
4478f95e 285 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
44b071c2
SJ
286 break;
287 case ERROR_INVALID_EMAIL:
0fbd1f3f 288 $page->trigError('Erreur : l\'email n\'est pas valide.');
44b071c2
SJ
289 break;
290 case ERROR_LOOP_EMAIL:
4478f95e 291 $page->trigError('Erreur : ' . $user->forlifeEmail()
44b071c2
SJ
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 }
2d997414 296 // Fetch existing email aliases.
b4503762
SJ
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 = {?}
08d33afc
SJ
302 ORDER BY NOT(s.type = \'alias_aux\'), s.email, d.name',
303 $user->id());
b4503762 304 $page->assign('alias', $alias->fetchAllAssoc());
a16bf141 305 $page->assign('best_email', $user->bestEmail());
b4503762 306
2d997414 307 $page->assign('emails', $redirect->emails);
aab4661d 308
2d997414 309 // Display GoogleApps acount information.
f5c4bf30 310 require_once 'googleapps.inc.php';
2d997414 311 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
b715c1e1
SJ
312
313 require_once 'emails.combobox.inc.php';
17c6e7bb 314 fill_email_combobox($page, array('job', 'stripped_directory'));
81b5b746 315 }
316
3b346b99 317 function handler_antispam($page, $filter_status = null, $redirection = null)
81b5b746 318 {
319 require_once 'emails.inc.php';
8f201b69
FB
320 $wp = new PlWikiPage('Xorg.Antispam');
321 $wp->buildCache();
81b5b746 322
323 $page->changeTpl('emails/antispam.tpl');
324
ea280814
SJ
325 $user = S::user();
326 $bogo = new Bogo($user);
3b346b99
SJ
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 }
81b5b746 333 }
3b346b99
SJ
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);
81b5b746 338 }
339
26ba053e 340 function handler_submit($page)
62ce6356 341 {
8f201b69
FB
342 $wp = new PlWikiPage('Xorg.Mails');
343 $wp->buildCache();
62ce6356 344 $page->changeTpl('emails/submit_spam.tpl');
345
40d428d8
VZ
346 if (Post::has('send_email')) {
347 S::assert_xsrf_token();
348
f3df6d38 349 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
15603084 350 if (!$upload) {
a7d35093 351 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
62ce6356 352 return;
353 }
15603084 354 $mime = $upload->contentType();
62ce6356 355 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
15603084 356 $upload->clear();
faefdbb7 357 $page->trigError('Le fichier ne contient pas un email complet');
62ce6356 358 return;
359 }
2d997414
VZ
360 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
361
62ce6356 362 global $globals;
2d997414 363 $box = $type . '@' . $globals->mail->domain;
62ce6356 364 $mailer = new PlMailer();
365 $mailer->addTo($box);
2d997414
VZ
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');
62ce6356 369 $mailer->send();
a7d35093 370 $page->trigSuccess('Le message a été transmis à ' . $box);
15603084 371 $upload->clear();
62ce6356 372 }
373 }
374
26ba053e 375 function handler_send($page)
81b5b746 376 {
81b5b746 377 $page->changeTpl('emails/send.tpl');
378
46f272fe 379 $page->setTitle('Envoyer un email');
81b5b746 380
381 // action si on recoit un formulaire
3360c04f 382 if (Post::has('save')) {
46504fb3
VZ
383 if (!S::has_xsrf_token()) {
384 return PL_FORBIDDEN;
385 }
386
3360c04f
FB
387 unset($_POST['save']);
388 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
ed06daba
FB
389 Post::set('to_contacts', explode(';', Post::s('to_contacts')));
390 Post::set('cc_contacts', explode(';', Post::s('cc_contacts')));
3360c04f 391 $data = serialize($_POST);
00ba8a74
SJ
392 XDB::execute('INSERT INTO email_send_save (uid, data)
393 VALUES ({?}, {?})
394 ON DUPLICATE KEY UPDATE data = VALUES(data)',
48e683dd 395 S::user()->id('uid'), $data);
3360c04f
FB
396 }
397 exit;
40d428d8
VZ
398 } else if (Env::v('submit') == 'Envoyer') {
399 S::assert_xsrf_token();
400
91a14f73 401 function getEmails($aliases)
402 {
403 if (!is_array($aliases)) {
404 return null;
405 }
2d5264c6
FB
406 $uf = new UserFilter(new UFC_Hrpid($aliases));
407 $users = $uf->iterUsers();
91a14f73 408 $ret = array();
2d5264c6
FB
409 while ($user = $users->next()) {
410 $ret[] = $user->forlife;
91a14f73 411 }
412 return join(', ', $ret);
413 }
414
5e68682e 415 $error = false;
da419622 416 foreach ($_FILES as &$file) {
f3df6d38 417 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 418 $page->trigError(PlUpload::$lastError);
5e68682e
FB
419 $error = true;
420 break;
da419622 421 }
422 }
423
5e68682e
FB
424 if (!$error) {
425 XDB::execute("DELETE FROM email_send_save
48e683dd
FB
426 WHERE uid = {?}",
427 S::user()->id());
5e68682e
FB
428
429 $to2 = getEmails(Env::v('to_contacts'));
430 $cc2 = getEmails(Env::v('cc_contacts'));
431 $txt = str_replace('^M', '', Env::v('contenu'));
3c7b9bad
SJ
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'));
5e68682e 437
6ff4f8c0
SJ
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 }
5e68682e 446 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 447 $page->trigError("Indique au moins un destinataire.");
6ff4f8c0
SJ
448 $error = true;
449 }
450
451 if ($error) {
f3df6d38 452 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
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); }
f3df6d38 462 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
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()) {
faefdbb7 472 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 473 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 474 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 475 } else {
a7d35093 476 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 477 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 478 }
81b5b746 479 }
480 }
481 } else {
3360c04f
FB
482 $res = XDB::query("SELECT data
483 FROM email_send_save
484 WHERE uid = {?}", S::i('uid'));
485 if ($res->numRows() == 0) {
f3df6d38 486 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 487 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
488 } else {
489 $data = unserialize($res->fetchOneCell());
490 $_REQUEST = array_merge($_REQUEST, $data);
491 }
81b5b746 492 }
493
2d5264c6
FB
494 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
495 new UFC_Registered()),
496 UserFilter::sortByName());
497 $contacts = $uf->getProfiles();
48e683dd 498 $page->assign('contacts', $contacts);
5e68682e 499 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 500 $page->assign('user', S::user());
81b5b746 501 }
502
26ba053e 503 function handler_test($page, $hruid = null)
5ff3f06b 504 {
e4ecada4
VZ
505 require_once 'emails.inc.php';
506
46504fb3
VZ
507 if (!S::has_xsrf_token()) {
508 return PL_FORBIDDEN;
509 }
d0c3e04d
VZ
510
511 // Retrieves the User object for the test email recipient.
dd70cd28 512 if (S::admin() && $hruid) {
d0c3e04d
VZ
513 $user = User::getSilent($hruid);
514 } else {
515 $user = S::user();
516 }
517 if (!$user) {
518 return PL_NOT_FOUND;
5ff3f06b 519 }
e4ecada4 520
d0c3e04d 521 // Sends the test email.
12a587df 522 $redirect = new Redirect($user);
e4ecada4
VZ
523
524 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 525 $mailer->assign('email', $user->bestEmail());
e4ecada4 526 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
527 $mailer->assign('display_name', $user->displayName());
528 $mailer->assign('sexe', $user->isFemale());
529 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
530 exit;
531 }
532
26ba053e 533 function handler_rewrite_in($page, $mail, $hash)
3d17e48f
FB
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} = '@';
b4503762
SJ
545 $res = XDB::query('SELECT COUNT(*)
546 FROM email_redirect_account
547 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
3d17e48f
FB
548 $mail, $hash);
549 $count = intval($res->fetchOneCell());
550 if ($count > 0) {
b4503762 551 XDB::query('UPDATE email_redirect_account
3d17e48f 552 SET allow_rewrite = true, hash = NULL
b4503762
SJ
553 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
554 $mail, $hash);
3d17e48f
FB
555 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
556 return;
557 }
558 return PL_NOT_FOUND;
559 }
560
26ba053e 561 function handler_rewrite_out($page, $mail, $hash)
3d17e48f
FB
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} = '@';
b4503762
SJ
573 $res = XDB::query('SELECT COUNT(*)
574 FROM email_redirect_account
575 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
3d17e48f
FB
576 $mail, $hash);
577 $count = intval($res->fetchOneCell());
578 if ($count > 0) {
579 global $globals;
b4503762
SJ
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 = {?}',
3d17e48f 584 $mail, $hash);
b4503762 585 XDB::query('UPDATE email_redirect_account
3d17e48f 586 SET allow_rewrite = false, hash = NULL
b4503762
SJ
587 WHERE redirect = {?} AND hash = {?}',
588 $mail, $hash);
589 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
3d17e48f
FB
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");
b4503762 594 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
3d17e48f
FB
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
26ba053e 602 function handler_imap_in($page, $hash = null, $login = null)
2ee43273
FB
603 {
604 $page->changeTpl('emails/imap_register.tpl');
12a587df 605 $user = null;
2ee43273 606 if (!empty($hash) || !empty($login)) {
12a587df
VZ
607 $user = User::getSilent($login);
608 if ($user) {
1bf36cd1
SJ
609 $req = XDB::query('SELECT 1
610 FROM newsletter_ins
611 WHERE uid = {?} AND hash = {?}',
612 $user->id(), $hash);
12a587df
VZ
613 if ($req->numRows() == 0) {
614 $user = null;
615 }
616 }
2ee43273
FB
617 }
618
b4503762 619 require_once 'emails.inc.php';
2ee43273 620 $page->assign('ok', false);
12a587df 621 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
5ad556d3 622 Email::activate_storage(S::user(), 'imap', Bogo::IMAP_DEFAULT);
2ee43273 623 $page->assign('ok', true);
2ab3486b
SJ
624 $page->assign('yourself', S::user()->displayName());
625 $page->assign('sexe', S::user()->isFemale());
12a587df 626 } else if (!S::logged() && $user) {
5ad556d3 627 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
2ee43273 628 $page->assign('ok', true);
2ab3486b 629 $page->assign('yourself', $user->displayName());
12a587df 630 $page->assign('sexe', $user->isFemale());
2ee43273
FB
631 }
632 }
633
26ba053e 634 function handler_broken($page, $warn = null, $email = null)
81b5b746 635 {
636 require_once 'emails.inc.php';
8f201b69
FB
637 $wp = new PlWikiPage('Xorg.PatteCassée');
638 $wp->buildCache();
81b5b746 639
640 global $globals;
641
642 $page->changeTpl('emails/broken.tpl');
643
40d428d8 644 if ($warn == 'warn' && $email) {
d4b25d1a 645 S::assert_xsrf_token();
40d428d8 646
a9fd3272 647 // Usual verifications.
81b5b746 648 $email = valide_email($email);
a9fd3272
SJ
649 $uid = XDB::fetchOneCell('SELECT uid
650 FROM email_redirect_account
651 WHERE redirect = {?}', $email);
652
2c93e70e
FB
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);
6bb2f79a 660 $page->trigSuccess('Email envoyé&nbsp;!');
81b5b746 661 }
40d428d8
VZ
662 } elseif (Post::has('email')) {
663 S::assert_xsrf_token();
664
a9fd3272 665 $email = Post::t('email');
81b5b746 666
f036c896 667 if (!User::isForeignEmailAddress($email)) {
81b5b746 668 $page->assign('neuneu', true);
669 } else {
a9fd3272
SJ
670 $user = mark_broken_email($email);
671 $page->assign('user', $user);
672 $page->assign('email', $email);
81b5b746 673 }
674 }
675 }
9e570fe0 676
26ba053e 677 function handler_duplicated($page, $action = 'list', $email = null)
9e570fe0 678 {
679 $page->changeTpl('emails/duplicated.tpl');
680
681 $states = array('pending' => 'En attente...',
a7de4ef7 682 'safe' => 'Pas d\'inquiétude',
9e570fe0 683 'unsafe' => 'Recherches en cours',
684 'dangerous' => 'Usurpations par cette adresse');
685 $page->assign('states', $states);
686
40d428d8
VZ
687 if (Post::has('action')) {
688 S::assert_xsrf_token();
46504fb3 689 }
9e570fe0 690 switch (Post::v('action')) {
46504fb3 691 case 'create':
9e570fe0 692 if (trim(Post::v('emailN')) != '') {
06f4daf9 693 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
9e570fe0 694 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
695 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
696 };
697 break;
698
46504fb3 699 case 'edit':
06f4daf9 700 Xdb::execute('UPDATE email_watch
9e570fe0 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
46504fb3 705 default:
9e570fe0 706 if ($action == 'delete' && !is_null($email)) {
06f4daf9 707 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
9e570fe0 708 }
709 }
710 if ($action != 'create' && $action != 'edit') {
711 $action = 'list';
712 }
713 $page->assign('action', $action);
714
715 if ($action == 'list') {
34b566f4
SJ
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');
9e570fe0 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') {
34b566f4
SJ
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\')
02db84f6 747 LEFT JOIN accounts AS a ON (w.uid = a.uid)
34b566f4
SJ
748 WHERE w.email = {?}
749 ORDER BY s.email',
750 $email);
9e570fe0 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 }
d4b25d1a 769
26ba053e 770 function handler_lost($page, $action = 'list', $email = null)
7727ffc7 771 {
772 $page->changeTpl('emails/lost.tpl');
eaf30d86 773
d4b25d1a 774 $page->assign('lost_emails',
73682f22 775 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
34b566f4
SJ
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
73682f22 784 ORDER BY pd.promo, a.hruid'));
7727ffc7 785 }
67e06366 786
26ba053e 787 function handler_broken_addr($page)
67e06366
SJ
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) {
35a22488
SJ
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)) {
a9fd3272
SJ
810 $nb = XDB::fetchOneCell('SELECT COUNT(*)
811 FROM email_redirect_account
812 WHERE redirect = {?}', $email);
813 if ($nb > 0) {
35a22488
SJ
814 $valid_emails[] = $email;
815 } else {
a9fd3272 816 $invalid_emails[] = $orig_email . ': no such redirection';
35a22488 817 }
67e06366
SJ
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 {
52da49d8
SJ
834 require_once 'notifs.inc.php';
835
67e06366 836 $broken_user_list = array();
52da49d8 837 $broken_user_email_count = array();
67e06366
SJ
838 $broken_list = explode("\n", $list);
839 sort($broken_list);
67e06366 840
a9fd3272
SJ
841 foreach ($broken_list as $email) {
842 if ($user = mark_broken_email($email, true)) {
dd092f56 843 if ($user['nb_mails'] > 0 && $user['notify']) {
67e06366 844 $mail = new PlMailer('emails/broken.mail.tpl');
dd092f56
SJ
845 $dest = User::getSilentWithUID($user['uid']);
846 $mail->setTo($dest);
a9fd3272 847 $mail->assign('user', $user);
67e06366
SJ
848 $mail->assign('email', $email);
849 $mail->send();
52da49d8
SJ
850 } else {
851 $profile = Profile::get($user['alias']);
852 WatchProfileUpdate::register($profile, 'broken');
67e06366
SJ
853 }
854
52da49d8
SJ
855 if (!isset($broken_user_list[$user['uid']])) {
856 $broken_user_list[$user['uid']] = array($email);
67e06366 857 } else {
52da49d8 858 $broken_user_list[$user['uid']][] = $email;
67e06366 859 }
52da49d8 860 $broken_user_email_count[$user['uid']] = $user['nb_mails'];
67e06366
SJ
861 }
862 }
863
a9fd3272
SJ
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()');
67e06366
SJ
872
873 // Output the list of users with recently broken addresses,
874 // along with the count of valid redirections.
023c46fb 875 pl_cached_content_headers('text/x-csv', 1);
67e06366
SJ
876
877 $csv = fopen('php://output', 'w');
52da49d8 878 fputcsv($csv, array('nom', 'promo', 'bounces', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
167c9007 879 $corpsList = DirEnum::getOptions(DirEnum::CURRENTCORPS);
52da49d8
SJ
880 foreach ($broken_user_list as $uid => $mails) {
881 $profile = Profile::get($uid);
882 $corps = $profile->getCorps();
167c9007 883 $current_corps = ($corps && $corps->current) ? $corpsList[$corps->current] : '';
52da49d8
SJ
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'];
67e06366 893 }
52da49d8
SJ
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)), ';');
67e06366
SJ
898 }
899 fclose($csv);
900 exit;
901 }
902 }
903 }
81b5b746 904}
905
a7de4ef7 906// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 907?>