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