Fixes entreprises edition (Closes #1123).
[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')) {
b715c1e1 252 $new_email = Env::v('email');
6ea6d9c1 253 if ($new_email == "new@example.org") {
b715c1e1
SJ
254 $new_email = Env::v('email_new');
255 }
aef0283b
VZ
256 $result = $redirect->add_email($new_email);
257 if ($result == ERROR_INVALID_EMAIL) {
b715c1e1
SJ
258 $page->assign('email', $new_email);
259 }
aef0283b 260 $page->assign('retour', $result);
81b5b746 261 } elseif (empty($actifs)) {
1060c854 262 $result = ERROR_INACTIVE_REDIRECTION;
81b5b746 263 } elseif (is_array($actifs)) {
1060c854 264 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
81b5b746 265 }
266 }
267
1060c854 268 switch ($result) {
44b071c2
SJ
269 case ERROR_INACTIVE_REDIRECTION:
270 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
4478f95e 271 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
44b071c2
SJ
272 break;
273 case ERROR_INVALID_EMAIL:
274 $page->trigError('Erreur: l\'email n\'est pas valide.');
275 break;
276 case ERROR_LOOP_EMAIL:
4478f95e 277 $page->trigError('Erreur : ' . $user->forlifeEmail()
44b071c2
SJ
278 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
279 . $globals->mail->domain2 . ' ni vers polytechnique.edu.');
280 break;
281 }
282
2d997414 283 // Fetch the @alias_dom email alias, if any.
08cce2ff 284 $res = XDB::query(
81b5b746 285 "SELECT alias
286 FROM virtual
287 INNER JOIN virtual_redirect USING(vid)
288 WHERE (redirect={?} OR redirect={?})
eaf30d86 289 AND alias LIKE '%@{$globals->mail->alias_dom}'",
2d997414
VZ
290 $user->forlifeEmail(),
291 // TODO: remove this über-ugly hack. The issue is that you need
292 // to remove all @m4x.org addresses in virtual_redirect first.
293 $user->login() . '@' . $globals->mail->domain2);
81b5b746 294 $melix = $res->fetchOneCell();
295 if ($melix) {
296 list($melix) = explode('@', $melix);
297 $page->assign('melix',$melix);
298 }
299
2d997414 300 // Fetch existing email aliases.
08cce2ff 301 $res = XDB::query(
81b5b746 302 "SELECT alias,expire
303 FROM aliases
fe13bc1d 304 WHERE uid={?} AND (type='a_vie' OR type='alias')
2d997414 305 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
81b5b746 306 $page->assign('alias', $res->fetchAllAssoc());
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';
314 fill_email_combobox($page);
81b5b746 315 }
316
b7582015 317 function handler_antispam(&$page, $statut_filtre = 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);
b7582015 327 if (isset($statut_filtre)) {
11ed26e5 328 $bogo->change($statut_filtre + 0);
81b5b746 329 }
2d997414 330 $page->assign('filtre', $bogo->level());
81b5b746 331 }
332
62ce6356 333 function handler_submit(&$page)
334 {
8f201b69
FB
335 $wp = new PlWikiPage('Xorg.Mails');
336 $wp->buildCache();
62ce6356 337 $page->changeTpl('emails/submit_spam.tpl');
338
40d428d8
VZ
339 if (Post::has('send_email')) {
340 S::assert_xsrf_token();
341
f3df6d38 342 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
15603084 343 if (!$upload) {
a7d35093 344 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
62ce6356 345 return;
346 }
15603084 347 $mime = $upload->contentType();
62ce6356 348 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
15603084 349 $upload->clear();
faefdbb7 350 $page->trigError('Le fichier ne contient pas un email complet');
62ce6356 351 return;
352 }
2d997414
VZ
353 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
354
62ce6356 355 global $globals;
2d997414 356 $box = $type . '@' . $globals->mail->domain;
62ce6356 357 $mailer = new PlMailer();
358 $mailer->addTo($box);
2d997414
VZ
359 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
360 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
361 $mailer->addUploadAttachment($upload, $type . '.mail');
62ce6356 362 $mailer->send();
a7d35093 363 $page->trigSuccess('Le message a été transmis à ' . $box);
15603084 364 $upload->clear();
62ce6356 365 }
366 }
367
81b5b746 368 function handler_send(&$page)
369 {
81b5b746 370 $page->changeTpl('emails/send.tpl');
da419622 371 $page->addJsLink('ajax.js');
81b5b746 372
46f272fe 373 $page->setTitle('Envoyer un email');
81b5b746 374
375 // action si on recoit un formulaire
3360c04f 376 if (Post::has('save')) {
46504fb3
VZ
377 if (!S::has_xsrf_token()) {
378 return PL_FORBIDDEN;
379 }
380
3360c04f
FB
381 unset($_POST['save']);
382 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
383 $_POST['to_contacts'] = explode(';', @$_POST['to_contacts']);
384 $_POST['cc_contacts'] = explode(';', @$_POST['cc_contacts']);
385 $data = serialize($_POST);
386 XDB::execute("REPLACE INTO email_send_save
48e683dd
FB
387 VALUES ({?}, {?})",
388 S::user()->id('uid'), $data);
3360c04f
FB
389 }
390 exit;
40d428d8
VZ
391 } else if (Env::v('submit') == 'Envoyer') {
392 S::assert_xsrf_token();
393
91a14f73 394 function getEmails($aliases)
395 {
396 if (!is_array($aliases)) {
397 return null;
398 }
2d5264c6
FB
399 $uf = new UserFilter(new UFC_Hrpid($aliases));
400 $users = $uf->iterUsers();
91a14f73 401 $ret = array();
2d5264c6
FB
402 while ($user = $users->next()) {
403 $ret[] = $user->forlife;
91a14f73 404 }
405 return join(', ', $ret);
406 }
407
5e68682e 408 $error = false;
da419622 409 foreach ($_FILES as &$file) {
f3df6d38 410 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 411 $page->trigError(PlUpload::$lastError);
5e68682e
FB
412 $error = true;
413 break;
da419622 414 }
415 }
416
5e68682e
FB
417 if (!$error) {
418 XDB::execute("DELETE FROM email_send_save
48e683dd
FB
419 WHERE uid = {?}",
420 S::user()->id());
5e68682e
FB
421
422 $to2 = getEmails(Env::v('to_contacts'));
423 $cc2 = getEmails(Env::v('cc_contacts'));
424 $txt = str_replace('^M', '', Env::v('contenu'));
3c7b9bad
SJ
425 $to = str_replace(';', ',', Env::t('to'));
426 $subj = Env::t('sujet');
427 $from = Env::t('from');
428 $cc = str_replace(';', ',', Env::t('cc'));
429 $bcc = str_replace(';', ',', Env::t('bcc'));
5e68682e 430
6ff4f8c0
SJ
431 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
432 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
433 $email = trim($email);
434 if ($email != '' && !preg_match($email_regex, $email)) {
435 $page->trigError("L'adresse email " . $email . ' est erronée.');
436 $error = true;
437 }
438 }
5e68682e 439 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 440 $page->trigError("Indique au moins un destinataire.");
6ff4f8c0
SJ
441 $error = true;
442 }
443
444 if ($error) {
f3df6d38 445 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
446 } else {
447 $mymail = new PlMailer();
448 $mymail->setFrom($from);
449 $mymail->setSubject($subj);
450 if (!empty($to)) { $mymail->addTo($to); }
451 if (!empty($cc)) { $mymail->addCc($cc); }
452 if (!empty($bcc)) { $mymail->addBcc($bcc); }
453 if (!empty($to2)) { $mymail->addTo($to2); }
454 if (!empty($cc2)) { $mymail->addCc($cc2); }
f3df6d38 455 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
456 foreach ($files as $name=>&$upload) {
457 $mymail->addUploadAttachment($upload, $name);
458 }
459 if (Env::v('nowiki')) {
460 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
461 } else {
462 $mymail->setWikiBody($txt);
463 }
464 if ($mymail->send()) {
faefdbb7 465 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 466 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 467 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 468 } else {
a7d35093 469 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 470 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 471 }
81b5b746 472 }
473 }
474 } else {
3360c04f
FB
475 $res = XDB::query("SELECT data
476 FROM email_send_save
477 WHERE uid = {?}", S::i('uid'));
478 if ($res->numRows() == 0) {
f3df6d38 479 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 480 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
481 } else {
482 $data = unserialize($res->fetchOneCell());
483 $_REQUEST = array_merge($_REQUEST, $data);
484 }
81b5b746 485 }
486
2d5264c6
FB
487 $uf = new UserFilter(new PFC_And(new UFC_Contact(S::user()),
488 new UFC_Registered()),
489 UserFilter::sortByName());
490 $contacts = $uf->getProfiles();
48e683dd 491 $page->assign('contacts', $contacts);
5e68682e 492 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 493 $page->assign('user', S::user());
81b5b746 494 }
495
d0c3e04d 496 function handler_test(&$page, $hruid = null)
5ff3f06b 497 {
e4ecada4
VZ
498 require_once 'emails.inc.php';
499
46504fb3
VZ
500 if (!S::has_xsrf_token()) {
501 return PL_FORBIDDEN;
502 }
d0c3e04d
VZ
503
504 // Retrieves the User object for the test email recipient.
dd70cd28 505 if (S::admin() && $hruid) {
d0c3e04d
VZ
506 $user = User::getSilent($hruid);
507 } else {
508 $user = S::user();
509 }
510 if (!$user) {
511 return PL_NOT_FOUND;
5ff3f06b 512 }
e4ecada4 513
d0c3e04d 514 // Sends the test email.
12a587df 515 $redirect = new Redirect($user);
e4ecada4
VZ
516
517 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 518 $mailer->assign('email', $user->bestEmail());
e4ecada4 519 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
520 $mailer->assign('display_name', $user->displayName());
521 $mailer->assign('sexe', $user->isFemale());
522 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
523 exit;
524 }
525
3d17e48f
FB
526 function handler_rewrite_in(&$page, $mail, $hash)
527 {
528 $page->changeTpl('emails/rewrite.tpl');
529 $page->assign('option', 'in');
530 if (empty($mail) || empty($hash)) {
531 return PL_NOT_FOUND;
532 }
533 $pos = strrpos($mail, '_');
534 if ($pos === false) {
535 return PL_NOT_FOUND;
536 }
537 $mail{$pos} = '@';
538 $res = XDB::query("SELECT COUNT(*)
539 FROM emails
540 WHERE email = {?} AND hash = {?}",
541 $mail, $hash);
542 $count = intval($res->fetchOneCell());
543 if ($count > 0) {
544 XDB::query("UPDATE emails
545 SET allow_rewrite = true, hash = NULL
546 WHERE email = {?} AND hash = {?}",
547 $mail, $hash);
548 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
549 return;
550 }
551 return PL_NOT_FOUND;
552 }
553
554 function handler_rewrite_out(&$page, $mail, $hash)
555 {
556 $page->changeTpl('emails/rewrite.tpl');
557 $page->assign('option', 'out');
558 if (empty($mail) || empty($hash)) {
559 return PL_NOT_FOUND;
560 }
561 $pos = strrpos($mail, '_');
562 if ($pos === false) {
563 return PL_NOT_FOUND;
564 }
565 $mail{$pos} = '@';
566 $res = XDB::query("SELECT COUNT(*)
567 FROM emails
568 WHERE email = {?} AND hash = {?}",
569 $mail, $hash);
570 $count = intval($res->fetchOneCell());
571 if ($count > 0) {
572 global $globals;
573 $res = XDB::query("SELECT e.email, e.rewrite, a.alias
574 FROM emails AS e
fe13bc1d 575 INNER JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
3d17e48f
FB
576 WHERE e.email = {?} AND e.hash = {?}",
577 $mail, $hash);
578 XDB::query("UPDATE emails
579 SET allow_rewrite = false, hash = NULL
580 WHERE email = {?} AND hash = {?}",
581 $mail, $hash);
582 list($mail, $rewrite, $forlife) = $res->fetchOneRow();
583 $mail = new PlMailer();
584 $mail->setFrom("webmaster@" . $globals->mail->domain);
585 $mail->addTo("support@" . $globals->mail->domain);
586 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
587 $mail->setTxtBody("$forlife a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
588 $mail->send();
589 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
590 return;
591 }
592 return PL_NOT_FOUND;
593 }
594
2ee43273
FB
595 function handler_imap_in(&$page, $hash = null, $login = null)
596 {
597 $page->changeTpl('emails/imap_register.tpl');
12a587df 598 $user = null;
2ee43273 599 if (!empty($hash) || !empty($login)) {
12a587df
VZ
600 $user = User::getSilent($login);
601 if ($user) {
1bf36cd1
SJ
602 $req = XDB::query('SELECT 1
603 FROM newsletter_ins
604 WHERE uid = {?} AND hash = {?}',
605 $user->id(), $hash);
12a587df
VZ
606 if ($req->numRows() == 0) {
607 $user = null;
608 }
609 }
2ee43273
FB
610 }
611
612 require_once('emails.inc.php');
613 $page->assign('ok', false);
12a587df
VZ
614 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
615 $storage = new EmailStorage(S::user(), 'imap');
2ee43273
FB
616 $storage->activate();
617 $page->assign('ok', true);
618 $page->assign('prenom', S::v('prenom'));
e2cea47d 619 $page->assign('sexe', S::v('femme'));
12a587df
VZ
620 } else if (!S::logged() && $user) {
621 $storage = new EmailStorage($user, 'imap');
2ee43273
FB
622 $storage->activate();
623 $page->assign('ok', true);
12a587df
VZ
624 $page->assign('prenom', $user->displayName());
625 $page->assign('sexe', $user->isFemale());
2ee43273
FB
626 }
627 }
628
81b5b746 629 function handler_broken(&$page, $warn = null, $email = null)
630 {
631 require_once 'emails.inc.php';
8f201b69
FB
632 $wp = new PlWikiPage('Xorg.PatteCassée');
633 $wp->buildCache();
81b5b746 634
635 global $globals;
636
637 $page->changeTpl('emails/broken.tpl');
638
40d428d8 639 if ($warn == 'warn' && $email) {
d4b25d1a 640 S::assert_xsrf_token();
40d428d8 641
81b5b746 642 $email = valide_email($email);
a7de4ef7 643 // vérifications d'usage
2c93e70e
FB
644 $uid = XDB::fetchOneCell("SELECT uid
645 FROM emails
646 WHERE email = {?}", $email);
647 if ($uid) {
648 $dest = User::getWithUID($uid);
649
650 $mail = new PlMailer('emails/broken-web.mail.tpl');
651 $mail->assign('email', $email);
652 $mail->assign('request', S::user());
653 $mail->sendTo($dest);
6bb2f79a 654 $page->trigSuccess('Email envoyé&nbsp;!');
81b5b746 655 }
40d428d8
VZ
656 } elseif (Post::has('email')) {
657 S::assert_xsrf_token();
658
5e2307dc 659 $email = valide_email(Post::v('email'));
81b5b746 660
661 list(,$fqdn) = explode('@', $email);
662 $fqdn = strtolower($fqdn);
40d428d8 663 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
81b5b746 664 $page->assign('neuneu', true);
665 } else {
666 $page->assign('email',$email);
2c93e70e
FB
667 $x = XDB::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne,
668 (count(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
669 FROM emails as e1
670 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
671 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
81b5b746 672 AND FIND_IN_SET('active', e2.flags)
673 AND e1.email != e2.email)
2c93e70e
FB
674 WHERE e1.email = {?}
675 GROUP BY e1.uid", $email);
676 if ($x) {
a7de4ef7 677 // on écrit dans la base que l'adresse est cassée
81b5b746 678 if (!$x['panne']) {
2c93e70e
FB
679 XDB::execute("UPDATE emails
680 SET panne=NOW(), last=NOW(), panne_level = 1
681 WHERE email = {?}", $email);
74938c82 682 } else {
2c93e70e
FB
683 XDB::execute("UPDATE emails
684 SET panne_level = 1
685 WHERE email = {?} AND panne_level = 0", $email);
81b5b746 686 }
2c93e70e 687 $x['user'] = User::getWithUID($x['uid']);
81b5b746 688 $page->assign_by_ref('x', $x);
689 }
690 }
691 }
692 }
9e570fe0 693
694 function handler_duplicated(&$page, $action = 'list', $email = null)
695 {
696 $page->changeTpl('emails/duplicated.tpl');
697
698 $states = array('pending' => 'En attente...',
a7de4ef7 699 'safe' => 'Pas d\'inquiétude',
9e570fe0 700 'unsafe' => 'Recherches en cours',
701 'dangerous' => 'Usurpations par cette adresse');
702 $page->assign('states', $states);
703
40d428d8
VZ
704 if (Post::has('action')) {
705 S::assert_xsrf_token();
46504fb3 706 }
9e570fe0 707 switch (Post::v('action')) {
46504fb3 708 case 'create':
9e570fe0 709 if (trim(Post::v('emailN')) != '') {
06f4daf9 710 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
9e570fe0 711 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
712 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
713 };
714 break;
715
46504fb3 716 case 'edit':
06f4daf9 717 Xdb::execute('UPDATE email_watch
9e570fe0 718 SET state = {?}, last = NOW(), uid = {?}, description = {?}
719 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
720 break;
721
46504fb3 722 default:
9e570fe0 723 if ($action == 'delete' && !is_null($email)) {
06f4daf9 724 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
9e570fe0 725 }
726 }
727 if ($action != 'create' && $action != 'edit') {
728 $action = 'list';
729 }
730 $page->assign('action', $action);
731
732 if ($action == 'list') {
733 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
06f4daf9 734 FROM email_watch AS w
ca6d07f4 735 LEFT JOIN emails AS e USING(email)
fe13bc1d 736 LEFT JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
9e570fe0 737 ORDER BY w.state, w.email, a.alias";
738 $it = Xdb::iterRow($sql);
739
740 $table = array();
741 $props = array();
742 while (list($email, $date, $state, $forlife) = $it->next()) {
743 if (count($props) == 0 || $props['mail'] != $email) {
744 if (count($props) > 0) {
745 $table[] = $props;
746 }
747 $props = array('mail' => $email,
748 'detection' => $date,
749 'state' => $state,
750 'users' => array($forlife));
751 } else {
752 $props['users'][] = $forlife;
753 }
754 }
755 if (count($props) > 0) {
756 $table[] = $props;
757 }
758 $page->assign('table', $table);
759 } elseif ($action == 'edit') {
760 $sql = "SELECT w.detection, w.state, w.last, w.description,
761 a1.alias AS edit, a2.alias AS forlife
06f4daf9 762 FROM email_watch AS w
fe13bc1d 763 LEFT JOIN aliases AS a1 ON (a1.uid = w.uid AND a1.type = 'a_vie')
9615c895 764 LEFT JOIN emails AS e ON (w.email = e.email)
fe13bc1d 765 LEFT JOIN aliases AS a2 ON (a2.uid = e.uid AND a2.type = 'a_vie')
9e570fe0 766 WHERE w.email = {?}
767 ORDER BY a2.alias";
768 $it = Xdb::iterRow($sql, $email);
769
770 $props = array();
771 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
772 if (count($props) == 0) {
773 $props = array('mail' => $email,
774 'detection' => $detection,
775 'state' => $state,
776 'last' => $last,
777 'description' => $description,
778 'edit' => $edit,
779 'users' => array($forlife));
780 } else {
781 $props['users'][] = $forlife;
782 }
783 }
784 $page->assign('doublon', $props);
785 }
786 }
d4b25d1a 787
7727ffc7 788 function handler_lost(&$page, $action = 'list', $email = null)
789 {
790 $page->changeTpl('emails/lost.tpl');
eaf30d86 791
d4b25d1a
FB
792 // TODO: Order by promo.
793 $page->assign('lost_emails',
794 XDB::iterator("SELECT a.uid, a.hruid
795 FROM accounts AS a
796 INNER JOIN email_options AS eo ON (eo.uid = a.uid)
797 LEFT JOIN emails AS e ON (a.uid = e.uid AND FIND_IN_SET('active', e.flags))
798 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', eo.storage) = 0 AND
799 a.state = 'active'
800 ORDER BY a.hruid"));
7727ffc7 801 }
67e06366
SJ
802
803 function handler_broken_addr(&$page)
804 {
805 require_once 'emails.inc.php';
806 $page->changeTpl('emails/broken_addr.tpl');
807
808 if (Env::has('sort_broken')) {
809 S::assert_xsrf_token();
810
811 $list = trim(Env::v('list'));
812 if ($list == '') {
813 $page->trigError('La liste est vide.');
814 } else {
815 $valid_emails = array();
816 $invalid_emails = array();
817 $broken_list = explode("\n", $list);
818 sort($broken_list);
819 foreach ($broken_list as $orig_email) {
35a22488
SJ
820 $orig_email = trim($orig_email);
821 if ($orig_email != '') {
822 $email = valide_email($orig_email);
823 if (empty($email) || $email == '@') {
824 $invalid_emails[] = trim($orig_email) . ': invalid email';
825 } elseif (!in_array($email, $valid_emails)) {
826 $res = XDB::query('SELECT COUNT(*)
827 FROM emails
828 WHERE email = {?}', $email);
829 if ($res->fetchOneCell() > 0) {
830 $valid_emails[] = $email;
831 } else {
832 $invalid_emails[] = "$orig_email: no such redirection";
833 }
67e06366
SJ
834 }
835 }
836 }
837
838 $page->assign('valid_emails', $valid_emails);
839 $page->assign('invalid_emails', $invalid_emails);
840 }
841 }
842
843 if (Env::has('process_broken')) {
844 S::assert_xsrf_token();
845
846 $list = trim(Env::v('list'));
847 if ($list == '') {
848 $page->trigError('La liste est vide.');
849 } else {
850 global $platal;
851
852 $broken_user_list = array();
853 $broken_list = explode("\n", $list);
854 sort($broken_list);
855 foreach ($broken_list as $orig_email) {
856 $email = valide_email(trim($orig_email));
857 if (empty($email) || $email == '@') {
858 continue;
859 }
860
861 $sel = XDB::query(
862 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
a06602ae 863 acc.full_name, a.alias
67e06366
SJ
864 FROM emails AS e1
865 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
866 AND e1.email != e2.email)
a06602ae 867 INNER JOIN accounts AS acc ON (e1.uid = acc.uid)
fe13bc1d 868 INNER JOIN aliases AS a ON (acc.uid = a.uid AND FIND_IN_SET('bestalias', a.flags))
67e06366
SJ
869 WHERE e1.email = {?}
870 GROUP BY e1.uid", $email);
871
872 if ($x = $sel->fetchOneAssoc()) {
873 if (!$x['panne']) {
874 XDB::execute('UPDATE emails
875 SET panne=NOW(), last=NOW(), panne_level = 1
876 WHERE email = {?}',
877 $email);
878 } else {
879 XDB::execute('UPDATE emails
880 SET last = CURDATE(), panne_level = panne_level + 1
881 WHERE email = {?}
882 AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
883 $email);
884 }
885
886 if (!empty($x['nb_mails'])) {
887 $mail = new PlMailer('emails/broken.mail.tpl');
a06602ae 888 $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
67e06366
SJ
889 . $globals->mail->domain . '>');
890 $mail->assign('x', $x);
891 $mail->assign('email', $email);
892 $mail->send();
893 }
894
895 if (!isset($broken_user_list[$x['alias']])) {
896 $broken_user_list[$x['alias']] = array($email);
897 } else {
898 $broken_user_list[$x['alias']][] = $email;
899 }
900 }
901 }
902
903 XDB::execute("UPDATE emails
904 SET panne_level = panne_level - 1
905 WHERE flags = 'active' AND panne_level > 1
906 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
907 XDB::execute("UPDATE emails
908 SET panne_level = 0
909 WHERE flags = 'active' AND panne_level = 1
910 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
911
912 // Output the list of users with recently broken addresses,
913 // along with the count of valid redirections.
35a22488 914 require_once 'notifs.inc.php';
3cb500d5 915 pl_content_headers("text/x-csv");
67e06366
SJ
916
917 $csv = fopen('php://output', 'w');
a06602ae 918 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url'), ';');
67e06366
SJ
919 foreach ($broken_user_list as $alias => $mails) {
920 $sel = Xdb::query(
a06602ae
RB
921 "SELECT acc.uid, count(e.email) AS nb_mails,
922 IFNULL(pd.public_name, acc.full_name) AS fullname,
e03a98e9
SJ
923 IFNULL(pd.promo, 0) AS promo
924 FROM aliases AS a
925 INNER JOIN accounts AS acc ON (a.uid = acc.uid)
926 LEFT JOIN emails AS e ON (e.uid = acc.uid
927 AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
928 LEFT JOIN account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
929 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
67e06366 930 WHERE a.alias = {?}
a06602ae 931 GROUP BY acc.uid", $alias);
67e06366
SJ
932
933 if ($x = $sel->fetchOneAssoc()) {
ae6cd633 934 if ($x['nb_mails'] == 0) {
e03a98e9
SJ
935 $user = User::getSilentWithUID($x['uid']);
936 $profile = $user->profile();
937 WatchProfileUpdate::register($profile, 'broken');
ae6cd633 938 }
a06602ae 939 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
6139d6cb
SJ
940 join(',', $mails), $x['nb_mails'],
941 'https://www.polytechnique.org/marketing/broken/' . $alias), ';');
67e06366
SJ
942 }
943 }
944 fclose($csv);
945 exit;
946 }
947 }
948 }
81b5b746 949}
950
a7de4ef7 951// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 952?>