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