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