Updates core.
[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 }
40279e62 466 if (Env::v('wiki') == 'text') {
5e68682e
FB
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());
40279e62
SJ
501 $preferences = XDB::fetchOneAssoc('SELECT from_email, from_format
502 FROM accounts
503 WHERE uid = {?}',
504 S::user()->id());
505 if ($preferences['from_email'] == '') {
506 $preferences['from_email'] = '"' . S::user()->fullName() . '" <' . S::user()->bestEmail() . '>';
507 }
508 $page->assign('preferences', $preferences);
81b5b746 509 }
510
26ba053e 511 function handler_test($page, $hruid = null)
5ff3f06b 512 {
e4ecada4
VZ
513 require_once 'emails.inc.php';
514
46504fb3
VZ
515 if (!S::has_xsrf_token()) {
516 return PL_FORBIDDEN;
517 }
d0c3e04d
VZ
518
519 // Retrieves the User object for the test email recipient.
dd70cd28 520 if (S::admin() && $hruid) {
d0c3e04d
VZ
521 $user = User::getSilent($hruid);
522 } else {
523 $user = S::user();
524 }
525 if (!$user) {
526 return PL_NOT_FOUND;
5ff3f06b 527 }
e4ecada4 528
d0c3e04d 529 // Sends the test email.
12a587df 530 $redirect = new Redirect($user);
e4ecada4
VZ
531
532 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 533 $mailer->assign('email', $user->bestEmail());
e4ecada4 534 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
535 $mailer->assign('display_name', $user->displayName());
536 $mailer->assign('sexe', $user->isFemale());
537 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
538 exit;
539 }
540
26ba053e 541 function handler_rewrite_in($page, $mail, $hash)
3d17e48f
FB
542 {
543 $page->changeTpl('emails/rewrite.tpl');
544 $page->assign('option', 'in');
545 if (empty($mail) || empty($hash)) {
546 return PL_NOT_FOUND;
547 }
548 $pos = strrpos($mail, '_');
549 if ($pos === false) {
550 return PL_NOT_FOUND;
551 }
552 $mail{$pos} = '@';
b4503762
SJ
553 $res = XDB::query('SELECT COUNT(*)
554 FROM email_redirect_account
555 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
3d17e48f
FB
556 $mail, $hash);
557 $count = intval($res->fetchOneCell());
558 if ($count > 0) {
b4503762 559 XDB::query('UPDATE email_redirect_account
3d17e48f 560 SET allow_rewrite = true, hash = NULL
b4503762
SJ
561 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
562 $mail, $hash);
3d17e48f
FB
563 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
564 return;
565 }
566 return PL_NOT_FOUND;
567 }
568
26ba053e 569 function handler_rewrite_out($page, $mail, $hash)
3d17e48f
FB
570 {
571 $page->changeTpl('emails/rewrite.tpl');
572 $page->assign('option', 'out');
573 if (empty($mail) || empty($hash)) {
574 return PL_NOT_FOUND;
575 }
576 $pos = strrpos($mail, '_');
577 if ($pos === false) {
578 return PL_NOT_FOUND;
579 }
580 $mail{$pos} = '@';
b4503762
SJ
581 $res = XDB::query('SELECT COUNT(*)
582 FROM email_redirect_account
583 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
3d17e48f
FB
584 $mail, $hash);
585 $count = intval($res->fetchOneCell());
586 if ($count > 0) {
587 global $globals;
b4503762
SJ
588 $res = XDB::query('SELECT e.redirect, e.rewrite, a.hruid
589 FROM email_redirect_account AS e
590 INNER JOIN accounts AS a ON (e.uid = a.uid)
591 WHERE e.redirect = {?} AND e.hash = {?}',
3d17e48f 592 $mail, $hash);
b4503762 593 XDB::query('UPDATE email_redirect_account
3d17e48f 594 SET allow_rewrite = false, hash = NULL
b4503762
SJ
595 WHERE redirect = {?} AND hash = {?}',
596 $mail, $hash);
597 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
3d17e48f
FB
598 $mail = new PlMailer();
599 $mail->setFrom("webmaster@" . $globals->mail->domain);
600 $mail->addTo("support@" . $globals->mail->domain);
601 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
b4503762 602 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
3d17e48f
FB
603 $mail->send();
604 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
605 return;
606 }
607 return PL_NOT_FOUND;
608 }
609
26ba053e 610 function handler_imap_in($page, $hash = null, $login = null)
2ee43273
FB
611 {
612 $page->changeTpl('emails/imap_register.tpl');
12a587df 613 $user = null;
2ee43273 614 if (!empty($hash) || !empty($login)) {
12a587df
VZ
615 $user = User::getSilent($login);
616 if ($user) {
1bf36cd1
SJ
617 $req = XDB::query('SELECT 1
618 FROM newsletter_ins
619 WHERE uid = {?} AND hash = {?}',
620 $user->id(), $hash);
12a587df
VZ
621 if ($req->numRows() == 0) {
622 $user = null;
623 }
624 }
2ee43273
FB
625 }
626
b4503762 627 require_once 'emails.inc.php';
2ee43273 628 $page->assign('ok', false);
12a587df 629 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
5ad556d3 630 Email::activate_storage(S::user(), 'imap', Bogo::IMAP_DEFAULT);
2ee43273 631 $page->assign('ok', true);
2ab3486b
SJ
632 $page->assign('yourself', S::user()->displayName());
633 $page->assign('sexe', S::user()->isFemale());
12a587df 634 } else if (!S::logged() && $user) {
5ad556d3 635 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
2ee43273 636 $page->assign('ok', true);
2ab3486b 637 $page->assign('yourself', $user->displayName());
12a587df 638 $page->assign('sexe', $user->isFemale());
2ee43273
FB
639 }
640 }
641
26ba053e 642 function handler_broken($page, $warn = null, $email = null)
81b5b746 643 {
644 require_once 'emails.inc.php';
8f201b69
FB
645 $wp = new PlWikiPage('Xorg.PatteCassée');
646 $wp->buildCache();
81b5b746 647
648 global $globals;
649
650 $page->changeTpl('emails/broken.tpl');
651
40d428d8 652 if ($warn == 'warn' && $email) {
d4b25d1a 653 S::assert_xsrf_token();
40d428d8 654
a9fd3272 655 // Usual verifications.
81b5b746 656 $email = valide_email($email);
a9fd3272
SJ
657 $uid = XDB::fetchOneCell('SELECT uid
658 FROM email_redirect_account
659 WHERE redirect = {?}', $email);
660
2c93e70e
FB
661 if ($uid) {
662 $dest = User::getWithUID($uid);
663
664 $mail = new PlMailer('emails/broken-web.mail.tpl');
665 $mail->assign('email', $email);
666 $mail->assign('request', S::user());
667 $mail->sendTo($dest);
6bb2f79a 668 $page->trigSuccess('Email envoyé&nbsp;!');
81b5b746 669 }
40d428d8
VZ
670 } elseif (Post::has('email')) {
671 S::assert_xsrf_token();
672
a9fd3272 673 $email = Post::t('email');
81b5b746 674
f036c896 675 if (!User::isForeignEmailAddress($email)) {
81b5b746 676 $page->assign('neuneu', true);
677 } else {
a9fd3272
SJ
678 $user = mark_broken_email($email);
679 $page->assign('user', $user);
680 $page->assign('email', $email);
81b5b746 681 }
682 }
683 }
9e570fe0 684
26ba053e 685 function handler_duplicated($page, $action = 'list', $email = null)
9e570fe0 686 {
687 $page->changeTpl('emails/duplicated.tpl');
688
689 $states = array('pending' => 'En attente...',
a7de4ef7 690 'safe' => 'Pas d\'inquiétude',
9e570fe0 691 'unsafe' => 'Recherches en cours',
692 'dangerous' => 'Usurpations par cette adresse');
693 $page->assign('states', $states);
694
40d428d8
VZ
695 if (Post::has('action')) {
696 S::assert_xsrf_token();
46504fb3 697 }
9e570fe0 698 switch (Post::v('action')) {
46504fb3 699 case 'create':
9e570fe0 700 if (trim(Post::v('emailN')) != '') {
06f4daf9 701 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
9e570fe0 702 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
703 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
704 };
705 break;
706
46504fb3 707 case 'edit':
06f4daf9 708 Xdb::execute('UPDATE email_watch
9e570fe0 709 SET state = {?}, last = NOW(), uid = {?}, description = {?}
710 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
711 break;
712
46504fb3 713 default:
9e570fe0 714 if ($action == 'delete' && !is_null($email)) {
06f4daf9 715 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
9e570fe0 716 }
717 }
718 if ($action != 'create' && $action != 'edit') {
719 $action = 'list';
720 }
721 $page->assign('action', $action);
722
723 if ($action == 'list') {
34b566f4
SJ
724 $it = XDB::iterRow('SELECT w.email, w.detection, w.state, s.email AS forlife
725 FROM email_watch AS w
726 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
727 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
728 ORDER BY w.state, w.email, s.email');
9e570fe0 729
730 $table = array();
731 $props = array();
732 while (list($email, $date, $state, $forlife) = $it->next()) {
733 if (count($props) == 0 || $props['mail'] != $email) {
734 if (count($props) > 0) {
735 $table[] = $props;
736 }
737 $props = array('mail' => $email,
738 'detection' => $date,
739 'state' => $state,
740 'users' => array($forlife));
741 } else {
742 $props['users'][] = $forlife;
743 }
744 }
745 if (count($props) > 0) {
746 $table[] = $props;
747 }
748 $page->assign('table', $table);
749 } elseif ($action == 'edit') {
34b566f4
SJ
750 $it = XDB::iterRow('SELECT w.detection, w.state, w.last, w.description,
751 a.hruid AS edit, s.email AS forlife
752 FROM email_watch AS w
753 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
754 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
02db84f6 755 LEFT JOIN accounts AS a ON (w.uid = a.uid)
34b566f4
SJ
756 WHERE w.email = {?}
757 ORDER BY s.email',
758 $email);
9e570fe0 759
760 $props = array();
761 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
762 if (count($props) == 0) {
763 $props = array('mail' => $email,
764 'detection' => $detection,
765 'state' => $state,
766 'last' => $last,
767 'description' => $description,
768 'edit' => $edit,
769 'users' => array($forlife));
770 } else {
771 $props['users'][] = $forlife;
772 }
773 }
774 $page->assign('doublon', $props);
775 }
776 }
d4b25d1a 777
26ba053e 778 function handler_lost($page, $action = 'list', $email = null)
7727ffc7 779 {
780 $page->changeTpl('emails/lost.tpl');
eaf30d86 781
d4b25d1a 782 $page->assign('lost_emails',
73682f22 783 XDB::iterator('SELECT a.uid, a.hruid, pd.promo
34b566f4
SJ
784 FROM accounts AS a
785 INNER JOIN account_types AS at ON (a.type = at.type)
786 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
787 AND er.type != \'imap\' AND er.type != \'homonym\')
788 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
789 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
790 WHERE a.state = \'active\' AND er.redirect IS NULL AND FIND_IN_SET(\'mail\', at.perms)
791 GROUP BY a.uid
73682f22 792 ORDER BY pd.promo, a.hruid'));
7727ffc7 793 }
67e06366 794
26ba053e 795 function handler_broken_addr($page)
67e06366
SJ
796 {
797 require_once 'emails.inc.php';
798 $page->changeTpl('emails/broken_addr.tpl');
799
800 if (Env::has('sort_broken')) {
801 S::assert_xsrf_token();
802
803 $list = trim(Env::v('list'));
804 if ($list == '') {
805 $page->trigError('La liste est vide.');
806 } else {
807 $valid_emails = array();
808 $invalid_emails = array();
809 $broken_list = explode("\n", $list);
810 sort($broken_list);
811 foreach ($broken_list as $orig_email) {
35a22488
SJ
812 $orig_email = trim($orig_email);
813 if ($orig_email != '') {
814 $email = valide_email($orig_email);
815 if (empty($email) || $email == '@') {
816 $invalid_emails[] = trim($orig_email) . ': invalid email';
817 } elseif (!in_array($email, $valid_emails)) {
a9fd3272
SJ
818 $nb = XDB::fetchOneCell('SELECT COUNT(*)
819 FROM email_redirect_account
820 WHERE redirect = {?}', $email);
821 if ($nb > 0) {
35a22488
SJ
822 $valid_emails[] = $email;
823 } else {
a9fd3272 824 $invalid_emails[] = $orig_email . ': no such redirection';
35a22488 825 }
67e06366
SJ
826 }
827 }
828 }
829
830 $page->assign('valid_emails', $valid_emails);
831 $page->assign('invalid_emails', $invalid_emails);
832 }
833 }
834
835 if (Env::has('process_broken')) {
836 S::assert_xsrf_token();
837
838 $list = trim(Env::v('list'));
839 if ($list == '') {
840 $page->trigError('La liste est vide.');
841 } else {
52da49d8
SJ
842 require_once 'notifs.inc.php';
843
67e06366 844 $broken_user_list = array();
52da49d8 845 $broken_user_email_count = array();
67e06366
SJ
846 $broken_list = explode("\n", $list);
847 sort($broken_list);
67e06366 848
a9fd3272
SJ
849 foreach ($broken_list as $email) {
850 if ($user = mark_broken_email($email, true)) {
dd092f56 851 if ($user['nb_mails'] > 0 && $user['notify']) {
67e06366 852 $mail = new PlMailer('emails/broken.mail.tpl');
dd092f56
SJ
853 $dest = User::getSilentWithUID($user['uid']);
854 $mail->setTo($dest);
a9fd3272 855 $mail->assign('user', $user);
67e06366
SJ
856 $mail->assign('email', $email);
857 $mail->send();
52da49d8
SJ
858 } else {
859 $profile = Profile::get($user['alias']);
860 WatchProfileUpdate::register($profile, 'broken');
67e06366
SJ
861 }
862
52da49d8
SJ
863 if (!isset($broken_user_list[$user['uid']])) {
864 $broken_user_list[$user['uid']] = array($email);
67e06366 865 } else {
52da49d8 866 $broken_user_list[$user['uid']][] = $email;
67e06366 867 }
52da49d8 868 $broken_user_email_count[$user['uid']] = $user['nb_mails'];
67e06366
SJ
869 }
870 }
871
a9fd3272
SJ
872 XDB::execute('UPDATE email_redirect_account
873 SET broken_level = broken_level - 1
874 WHERE flags = \'active\' AND broken_level > 1
875 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()');
876 XDB::execute('UPDATE email_redirect_account
877 SET broken_level = 0
878 WHERE flags = \'active\' AND broken_level = 1
879 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()');
67e06366
SJ
880
881 // Output the list of users with recently broken addresses,
882 // along with the count of valid redirections.
023c46fb 883 pl_cached_content_headers('text/x-csv', 1);
67e06366
SJ
884
885 $csv = fopen('php://output', 'w');
52da49d8 886 fputcsv($csv, array('nom', 'promo', 'bounces', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
167c9007 887 $corpsList = DirEnum::getOptions(DirEnum::CURRENTCORPS);
52da49d8
SJ
888 foreach ($broken_user_list as $uid => $mails) {
889 $profile = Profile::get($uid);
890 $corps = $profile->getCorps();
167c9007 891 $current_corps = ($corps && $corps->current) ? $corpsList[$corps->current] : '';
52da49d8
SJ
892 $jobs = $profile->getJobs();
893 $companies = array();
894 foreach ($jobs as $job) {
895 $companies[] = $job->company->name;
896 }
897 $networkings = $profile->getNetworking(Profile::NETWORKING_ALL);
898 $networking_list = array();
899 foreach ($networkings as $networking) {
900 $networking_list[] = $networking['address'];
67e06366 901 }
52da49d8
SJ
902 fputcsv($csv, array($profile->fullName(), $profile->promo(),
903 join(',', $mails), $broken_user_email_count[$uid],
904 'https://www.polytechnique.org/marketing/broken/' . $profile->hrid(),
905 $current_corps, implode(',', $companies), implode(',', $networking_list)), ';');
67e06366
SJ
906 }
907 fclose($csv);
908 exit;
909 }
910 }
911 }
81b5b746 912}
913
a7de4ef7 914// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 915?>