Rename utilisateurs.tpl in user.tpl.
[platal.git] / modules / email.php
CommitLineData
81b5b746 1<?php
2/***************************************************************************
8d84c630 3 * Copyright (C) 2003-2009 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'),
81b5b746 44 );
45 }
46
b7582015 47 function handler_emails(&$page, $action = null, $email = null)
81b5b746 48 {
49 global $globals;
e97e9b8f 50 require_once 'emails.inc.php';
81b5b746 51
52 $page->changeTpl('emails/index.tpl');
46f272fe 53 $page->setTitle('Mes emails');
81b5b746 54
2d997414 55 $user = S::user();
81b5b746 56
2d997414 57 // Apply the bestalias change request.
b7582015 58 if ($action == 'best' && $email) {
46504fb3
VZ
59 if (!S::has_xsrf_token()) {
60 return PL_FORBIDDEN;
61 }
62
2d997414
VZ
63 XDB::execute("UPDATE aliases
64 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
65 WHERE id = {?}", $user->id());
66 XDB::execute("UPDATE aliases
67 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
68 WHERE id = {?} AND alias = {?}", $user->id(), $email);
69
70 // As having a non-null bestalias value is critical in
71 // plat/al's code, we do an a posteriori check on the
72 // validity of the bestalias.
73 fix_bestalias($user);
81b5b746 74 }
75
2d997414 76 // Fetch and display aliases.
81b5b746 77 $sql = "SELECT alias, (type='a_vie') AS a_vie,
78 (alias REGEXP '\\\\.[0-9]{2}$') AS cent_ans,
79 FIND_IN_SET('bestalias',flags) AS best, expire
80 FROM aliases
81 WHERE id = {?} AND type!='homonyme'
82 ORDER BY LENGTH(alias)";
2d997414 83 $page->assign('aliases', XDB::iterator($sql, $user->id()));
81b5b746 84
2d997414
VZ
85 // Check for homonyms.
86 $homonyme = XDB::query(
87 "SELECT alias
88 FROM aliases
89 INNER JOIN homonymes ON (id = homonyme_id)
90 WHERE user_id = {?} AND type = 'homonyme'", $user->id());
e97e9b8f 91 $page->assign('homonyme', $homonyme->fetchOneCell());
e1547442 92
2d997414
VZ
93 // Display active redirections.
94 $redirect = new Redirect($user);
e97e9b8f 95 $page->assign('mails', $redirect->active_emails());
81b5b746 96
2d997414 97 // Display, when available, the @alias_dom email alias.
08cce2ff 98 $res = XDB::query(
81b5b746 99 "SELECT alias
100 FROM virtual AS v
101 INNER JOIN virtual_redirect AS vr USING(vid)
eaf30d86 102 WHERE (redirect={?} OR redirect={?})
81b5b746 103 AND alias LIKE '%@{$globals->mail->alias_dom}'",
2d997414
VZ
104 $user->forlifeEmail(),
105 // TODO: remove this über-ugly hack. The issue is that you need
106 // to remove all @m4x.org addresses in virtual_redirect first.
107 $user->login() . '@' . $globals->mail->domain2);
81b5b746 108 $page->assign('melix', $res->fetchOneCell());
81b5b746 109 }
110
111 function handler_alias(&$page, $action = null, $value = null)
112 {
113 require_once 'validations.inc.php';
114
115 global $globals;
116
117 $page->changeTpl('emails/alias.tpl');
46f272fe 118 $page->setTitle('Alias melix.net');
81b5b746 119
2d997414
VZ
120 $user = S::user();
121 $page->assign('demande', AliasReq::get_request($user->id()));
81b5b746 122
2d997414 123 // Remove the email alias.
40d428d8
VZ
124 if ($action == 'delete' && $value) {
125 S::assert_xsrf_token();
126
08cce2ff 127 XDB::execute(
2d997414
VZ
128 "DELETE virtual, virtual_redirect
129 FROM virtual
130 INNER JOIN virtual_redirect USING (vid)
131 WHERE alias = {?} AND (redirect = {?} OR redirect = {?})",
3e53a496 132 $value, $user->forlifeEmail(), $user->m4xForlifeEmail());
81b5b746 133 }
134
2d997414 135 // Fetch existing @alias_dom aliases.
3e53a496
FB
136 $alias = $user->emailAlias();
137 $visibility = $user->hasProfile() && $user->profile()->alias_pub;
81b5b746 138
40d428d8
VZ
139 if ($action == 'ask' && Env::has('alias') && Env::has('raison')) {
140 S::assert_xsrf_token();
81b5b746 141
40d428d8 142 //Si l'utilisateur vient de faire une damande
5e2307dc 143 $alias = Env::v('alias');
144 $raison = Env::v('raison');
6a4f0f01 145 $public = (Env::v('public', 'off') == 'on') ? 'public' : 'private';
81b5b746 146
147 $page->assign('r_alias', $alias);
148 $page->assign('r_raison', $raison);
149 if ($public == 'public') {
150 $page->assign('r_public', true);
151 }
152
a7de4ef7 153 //Quelques vérifications sur l'alias (caractères spéciaux)
3e53a496 154 if (!preg_match("/^[a-zA-Z0-9\-.]{3,20}$/", $alias)) {
a7d35093
FB
155 $page->trigError("L'adresse demandée n'est pas valide."
156 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
157 . " et qu'elle ne contient que des lettres non accentuées,"
158 . " des chiffres ou les caractères - et .");
fd8f77de 159 return;
81b5b746 160 } else {
3e53a496
FB
161 $alias_mail = $alias.'@'.$globals->mail->alias_dom;
162
a7de4ef7 163 //vérifier que l'alias n'est pas déja pris
3e53a496
FB
164 $res = XDB::query('SELECT COUNT(*)
165 FROM virtual
166 WHERE alias={?}',
167 $alias_mail);
81b5b746 168 if ($res->fetchOneCell() > 0) {
3e53a496
FB
169 $page->trigError("L'alias $alias_mail a déja été attribué.
170 Tu ne peux donc pas l'obtenir.");
fd8f77de 171 return;
81b5b746 172 }
173
a7de4ef7 174 //vérifier que l'alias n'est pas déja en demande
3e53a496 175 $it = new ValidateIterator();
81b5b746 176 while($req = $it->next()) {
3e53a496
FB
177 if ($req->type == 'alias' and $req->alias == $alias_mail) {
178 $page->trigError("L'alias $alias_mail a déja été demandé.
81b5b746 179 Tu ne peux donc pas l'obtenir pour l'instant.");
fd8f77de 180 return ;
81b5b746 181 }
182 }
183
a7de4ef7 184 //Insertion de la demande dans la base, écrase les requêtes précédente
2d997414 185 $myalias = new AliasReq($user, $alias, $raison, $public);
81b5b746 186 $myalias->submit();
187 $page->assign('success',$alias);
fd8f77de 188 return;
81b5b746 189 }
46504fb3
VZ
190 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
191 if (!S::has_xsrf_token()) {
192 return PL_FORBIDDEN;
193 }
194
3e53a496
FB
195 if ($user->hasProfile()) {
196 XDB::execute("UPDATE profiles
197 SET alias_pub = {?}
198 WHERE pid = {?}",
199 $value, $user->profile()->id());
81b5b746 200 }
3e53a496 201 $visibility = ($value == 'public');
81b5b746 202 }
203
3e53a496
FB
204 $page->assign('actuel', $alias);
205 $page->assign('user', $user);
206 $page->assign('mail_public', $visibility);
81b5b746 207 }
208
209 function handler_redirect(&$page, $action = null, $email = null)
210 {
211 global $globals;
212
213 require_once 'emails.inc.php';
214
215 $page->changeTpl('emails/redirect.tpl');
216
2d997414
VZ
217 $user = S::user();
218 $page->assign_by_ref('user', $user);
219 $page->assign('eleve', $user->promo() >= date("Y") - 5);
3b83212e 220
2d997414 221 $redirect = new Redirect($user);
81b5b746 222
6d6b65bf 223 // FS#703 : $_GET is urldecoded twice, hence
224 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
225 // Since there can be no spaces in emails, we can fix this with :
226 $email = str_replace(' ', '+', $email);
227
2d997414 228 // Apply email redirection change requests.
1060c854 229 $result = SUCCESS;
81b5b746 230 if ($action == 'remove' && $email) {
1060c854 231 $result = $redirect->delete_email($email);
81b5b746 232 }
e1547442
FB
233
234 if ($action == 'active' && $email) {
235 $redirect->modify_one_email($email, true);
236 }
237
238 if ($action == 'inactive' && $email) {
239 $redirect->modify_one_email($email, false);
240 }
241
242 if ($action == 'rewrite' && $email) {
243 $rewrite = @func_get_arg(3);
244 $redirect->modify_one_email_redirect($email, $rewrite);
245 }
246
40d428d8
VZ
247 if (Env::has('emailop')) {
248 S::assert_xsrf_token();
249
5e2307dc 250 $actifs = Env::v('emails_actifs', Array());
b7582015 251 print_r(Env::v('emails_rewrite'));
5e2307dc 252 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
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) {
b715c1e1
SJ
259 $page->assign('email', $new_email);
260 }
aef0283b 261 $page->assign('retour', $result);
81b5b746 262 } elseif (empty($actifs)) {
1060c854 263 $result = ERROR_INACTIVE_REDIRECTION;
81b5b746 264 } elseif (is_array($actifs)) {
1060c854 265 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
81b5b746 266 }
267 }
268
1060c854 269 switch ($result) {
44b071c2
SJ
270 case ERROR_INACTIVE_REDIRECTION:
271 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
4478f95e 272 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
44b071c2
SJ
273 break;
274 case ERROR_INVALID_EMAIL:
275 $page->trigError('Erreur: l\'email n\'est pas valide.');
276 break;
277 case ERROR_LOOP_EMAIL:
4478f95e 278 $page->trigError('Erreur : ' . $user->forlifeEmail()
44b071c2
SJ
279 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
280 . $globals->mail->domain2 . ' ni vers polytechnique.edu.');
281 break;
282 }
283
2d997414 284 // Fetch the @alias_dom email alias, if any.
08cce2ff 285 $res = XDB::query(
81b5b746 286 "SELECT alias
287 FROM virtual
288 INNER JOIN virtual_redirect USING(vid)
289 WHERE (redirect={?} OR redirect={?})
eaf30d86 290 AND alias LIKE '%@{$globals->mail->alias_dom}'",
2d997414
VZ
291 $user->forlifeEmail(),
292 // TODO: remove this über-ugly hack. The issue is that you need
293 // to remove all @m4x.org addresses in virtual_redirect first.
294 $user->login() . '@' . $globals->mail->domain2);
81b5b746 295 $melix = $res->fetchOneCell();
296 if ($melix) {
297 list($melix) = explode('@', $melix);
298 $page->assign('melix',$melix);
299 }
300
2d997414 301 // Fetch existing email aliases.
08cce2ff 302 $res = XDB::query(
81b5b746 303 "SELECT alias,expire
304 FROM aliases
305 WHERE id={?} AND (type='a_vie' OR type='alias')
2d997414 306 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
81b5b746 307 $page->assign('alias', $res->fetchAllAssoc());
2d997414 308 $page->assign('emails', $redirect->emails);
aab4661d 309
2d997414 310 // Display GoogleApps acount information.
f5c4bf30 311 require_once 'googleapps.inc.php';
2d997414 312 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
b715c1e1
SJ
313
314 require_once 'emails.combobox.inc.php';
315 fill_email_combobox($page);
81b5b746 316 }
317
b7582015 318 function handler_antispam(&$page, $statut_filtre = null)
81b5b746 319 {
320 require_once 'emails.inc.php';
8f201b69
FB
321 $wp = new PlWikiPage('Xorg.Antispam');
322 $wp->buildCache();
81b5b746 323
324 $page->changeTpl('emails/antispam.tpl');
325
12a587df 326 $bogo = new Bogo(S::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
387 VALUES ({?}, {?})", S::i('uid'), $data);
388 }
389 exit;
40d428d8
VZ
390 } else if (Env::v('submit') == 'Envoyer') {
391 S::assert_xsrf_token();
392
91a14f73 393 function getEmails($aliases)
394 {
395 if (!is_array($aliases)) {
396 return null;
397 }
398 $rel = Env::v('contacts');
399 $ret = array();
400 foreach ($aliases as $alias) {
401 $ret[$alias] = $rel[$alias];
402 }
403 return join(', ', $ret);
404 }
405
5e68682e 406 $error = false;
da419622 407 foreach ($_FILES as &$file) {
f3df6d38 408 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 409 $page->trigError(PlUpload::$lastError);
5e68682e
FB
410 $error = true;
411 break;
da419622 412 }
413 }
414
5e68682e
FB
415 if (!$error) {
416 XDB::execute("DELETE FROM email_send_save
417 WHERE uid = {?}", S::i('uid'));
418
419 $to2 = getEmails(Env::v('to_contacts'));
420 $cc2 = getEmails(Env::v('cc_contacts'));
421 $txt = str_replace('^M', '', Env::v('contenu'));
422 $to = Env::v('to');
423 $subj = Env::v('sujet');
424 $from = Env::v('from');
425 $cc = trim(Env::v('cc'));
426 $bcc = trim(Env::v('bcc'));
427
428 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 429 $page->trigError("Indique au moins un destinataire.");
f3df6d38 430 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
431 } else {
432 $mymail = new PlMailer();
433 $mymail->setFrom($from);
434 $mymail->setSubject($subj);
435 if (!empty($to)) { $mymail->addTo($to); }
436 if (!empty($cc)) { $mymail->addCc($cc); }
437 if (!empty($bcc)) { $mymail->addBcc($bcc); }
438 if (!empty($to2)) { $mymail->addTo($to2); }
439 if (!empty($cc2)) { $mymail->addCc($cc2); }
f3df6d38 440 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
441 foreach ($files as $name=>&$upload) {
442 $mymail->addUploadAttachment($upload, $name);
443 }
444 if (Env::v('nowiki')) {
445 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
446 } else {
447 $mymail->setWikiBody($txt);
448 }
449 if ($mymail->send()) {
faefdbb7 450 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 451 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 452 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 453 } else {
a7d35093 454 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 455 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 456 }
81b5b746 457 }
458 }
459 } else {
3360c04f
FB
460 $res = XDB::query("SELECT data
461 FROM email_send_save
462 WHERE uid = {?}", S::i('uid'));
463 if ($res->numRows() == 0) {
f3df6d38 464 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 465 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
466 } else {
467 $data = unserialize($res->fetchOneCell());
468 $_REQUEST = array_merge($_REQUEST, $data);
469 }
81b5b746 470 }
471
08cce2ff 472 $res = XDB::query(
57a29e19
FB
473 "SELECT ac.full_name, a.alias as forlife
474 FROM accounts AS ac
475 INNER JOIN contacts AS c ON (ac.uid = c.contact)
476 INNER JOIN aliases AS a ON (ac.uid = a.id AND FIND_IN_SET('bestalias', a.flags))
81b5b746 477 WHERE c.uid = {?}
57a29e19 478 ORDER BY ac.full_name", S::i('uid'));
81b5b746 479 $page->assign('contacts', $res->fetchAllAssoc());
5e68682e 480 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 481 $page->assign('user', S::user());
81b5b746 482 }
483
d0c3e04d 484 function handler_test(&$page, $hruid = null)
5ff3f06b 485 {
e4ecada4
VZ
486 require_once 'emails.inc.php';
487
46504fb3
VZ
488 if (!S::has_xsrf_token()) {
489 return PL_FORBIDDEN;
490 }
d0c3e04d
VZ
491
492 // Retrieves the User object for the test email recipient.
dd70cd28 493 if (S::admin() && $hruid) {
d0c3e04d
VZ
494 $user = User::getSilent($hruid);
495 } else {
496 $user = S::user();
497 }
498 if (!$user) {
499 return PL_NOT_FOUND;
5ff3f06b 500 }
e4ecada4 501
d0c3e04d 502 // Sends the test email.
12a587df 503 $redirect = new Redirect($user);
e4ecada4
VZ
504
505 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 506 $mailer->assign('email', $user->bestEmail());
e4ecada4 507 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
508 $mailer->assign('display_name', $user->displayName());
509 $mailer->assign('sexe', $user->isFemale());
510 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
511 exit;
512 }
513
3d17e48f
FB
514 function handler_rewrite_in(&$page, $mail, $hash)
515 {
516 $page->changeTpl('emails/rewrite.tpl');
517 $page->assign('option', 'in');
518 if (empty($mail) || empty($hash)) {
519 return PL_NOT_FOUND;
520 }
521 $pos = strrpos($mail, '_');
522 if ($pos === false) {
523 return PL_NOT_FOUND;
524 }
525 $mail{$pos} = '@';
526 $res = XDB::query("SELECT COUNT(*)
527 FROM emails
528 WHERE email = {?} AND hash = {?}",
529 $mail, $hash);
530 $count = intval($res->fetchOneCell());
531 if ($count > 0) {
532 XDB::query("UPDATE emails
533 SET allow_rewrite = true, hash = NULL
534 WHERE email = {?} AND hash = {?}",
535 $mail, $hash);
536 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
537 return;
538 }
539 return PL_NOT_FOUND;
540 }
541
542 function handler_rewrite_out(&$page, $mail, $hash)
543 {
544 $page->changeTpl('emails/rewrite.tpl');
545 $page->assign('option', 'out');
546 if (empty($mail) || empty($hash)) {
547 return PL_NOT_FOUND;
548 }
549 $pos = strrpos($mail, '_');
550 if ($pos === false) {
551 return PL_NOT_FOUND;
552 }
553 $mail{$pos} = '@';
554 $res = XDB::query("SELECT COUNT(*)
555 FROM emails
556 WHERE email = {?} AND hash = {?}",
557 $mail, $hash);
558 $count = intval($res->fetchOneCell());
559 if ($count > 0) {
560 global $globals;
561 $res = XDB::query("SELECT e.email, e.rewrite, a.alias
562 FROM emails AS e
563 INNER JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
564 WHERE e.email = {?} AND e.hash = {?}",
565 $mail, $hash);
566 XDB::query("UPDATE emails
567 SET allow_rewrite = false, hash = NULL
568 WHERE email = {?} AND hash = {?}",
569 $mail, $hash);
570 list($mail, $rewrite, $forlife) = $res->fetchOneRow();
571 $mail = new PlMailer();
572 $mail->setFrom("webmaster@" . $globals->mail->domain);
573 $mail->addTo("support@" . $globals->mail->domain);
574 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
575 $mail->setTxtBody("$forlife a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
576 $mail->send();
577 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
578 return;
579 }
580 return PL_NOT_FOUND;
581 }
582
2ee43273
FB
583 function handler_imap_in(&$page, $hash = null, $login = null)
584 {
585 $page->changeTpl('emails/imap_register.tpl');
12a587df 586 $user = null;
2ee43273 587 if (!empty($hash) || !empty($login)) {
12a587df
VZ
588 $user = User::getSilent($login);
589 if ($user) {
590 $req = XDB::query("SELECT 1 FROM newsletter_ins WHERE user_id = {?} AND hash = {?}", $user->id(), $hash);
591 if ($req->numRows() == 0) {
592 $user = null;
593 }
594 }
2ee43273
FB
595 }
596
597 require_once('emails.inc.php');
598 $page->assign('ok', false);
12a587df
VZ
599 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
600 $storage = new EmailStorage(S::user(), 'imap');
2ee43273
FB
601 $storage->activate();
602 $page->assign('ok', true);
603 $page->assign('prenom', S::v('prenom'));
e2cea47d 604 $page->assign('sexe', S::v('femme'));
12a587df
VZ
605 } else if (!S::logged() && $user) {
606 $storage = new EmailStorage($user, 'imap');
2ee43273
FB
607 $storage->activate();
608 $page->assign('ok', true);
12a587df
VZ
609 $page->assign('prenom', $user->displayName());
610 $page->assign('sexe', $user->isFemale());
2ee43273
FB
611 }
612 }
613
81b5b746 614 function handler_broken(&$page, $warn = null, $email = null)
615 {
616 require_once 'emails.inc.php';
8f201b69
FB
617 $wp = new PlWikiPage('Xorg.PatteCassée');
618 $wp->buildCache();
81b5b746 619
620 global $globals;
621
622 $page->changeTpl('emails/broken.tpl');
623
40d428d8 624 if ($warn == 'warn' && $email) {
d4b25d1a 625 S::assert_xsrf_token();
40d428d8 626
81b5b746 627 $email = valide_email($email);
a7de4ef7 628 // vérifications d'usage
2c93e70e
FB
629 $uid = XDB::fetchOneCell("SELECT uid
630 FROM emails
631 WHERE email = {?}", $email);
632 if ($uid) {
633 $dest = User::getWithUID($uid);
634
635 $mail = new PlMailer('emails/broken-web.mail.tpl');
636 $mail->assign('email', $email);
637 $mail->assign('request', S::user());
638 $mail->sendTo($dest);
faefdbb7 639 $page->trigSuccess("Email envoyé !");
81b5b746 640 }
40d428d8
VZ
641 } elseif (Post::has('email')) {
642 S::assert_xsrf_token();
643
5e2307dc 644 $email = valide_email(Post::v('email'));
81b5b746 645
646 list(,$fqdn) = explode('@', $email);
647 $fqdn = strtolower($fqdn);
40d428d8 648 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
81b5b746 649 $page->assign('neuneu', true);
650 } else {
651 $page->assign('email',$email);
2c93e70e
FB
652 $x = XDB::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne,
653 (count(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
654 FROM emails as e1
655 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
656 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
81b5b746 657 AND FIND_IN_SET('active', e2.flags)
658 AND e1.email != e2.email)
2c93e70e
FB
659 WHERE e1.email = {?}
660 GROUP BY e1.uid", $email);
661 if ($x) {
a7de4ef7 662 // on écrit dans la base que l'adresse est cassée
81b5b746 663 if (!$x['panne']) {
2c93e70e
FB
664 XDB::execute("UPDATE emails
665 SET panne=NOW(), last=NOW(), panne_level = 1
666 WHERE email = {?}", $email);
74938c82 667 } else {
2c93e70e
FB
668 XDB::execute("UPDATE emails
669 SET panne_level = 1
670 WHERE email = {?} AND panne_level = 0", $email);
81b5b746 671 }
2c93e70e 672 $x['user'] = User::getWithUID($x['uid']);
81b5b746 673 $page->assign_by_ref('x', $x);
674 }
675 }
676 }
677 }
9e570fe0 678
679 function handler_duplicated(&$page, $action = 'list', $email = null)
680 {
681 $page->changeTpl('emails/duplicated.tpl');
682
683 $states = array('pending' => 'En attente...',
a7de4ef7 684 'safe' => 'Pas d\'inquiétude',
9e570fe0 685 'unsafe' => 'Recherches en cours',
686 'dangerous' => 'Usurpations par cette adresse');
687 $page->assign('states', $states);
688
40d428d8
VZ
689 if (Post::has('action')) {
690 S::assert_xsrf_token();
46504fb3 691 }
9e570fe0 692 switch (Post::v('action')) {
46504fb3 693 case 'create':
9e570fe0 694 if (trim(Post::v('emailN')) != '') {
695 Xdb::execute('INSERT IGNORE INTO emails_watch (email, state, detection, last, uid, description)
696 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
697 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
698 };
699 break;
700
46504fb3 701 case 'edit':
9e570fe0 702 Xdb::execute('UPDATE emails_watch
703 SET state = {?}, last = NOW(), uid = {?}, description = {?}
704 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
705 break;
706
46504fb3 707 default:
9e570fe0 708 if ($action == 'delete' && !is_null($email)) {
709 Xdb::execute('DELETE FROM emails_watch WHERE email = {?}', $email);
710 }
711 }
712 if ($action != 'create' && $action != 'edit') {
713 $action = 'list';
714 }
715 $page->assign('action', $action);
716
717 if ($action == 'list') {
718 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
719 FROM emails_watch AS w
ca6d07f4 720 LEFT JOIN emails AS e USING(email)
721 LEFT JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
9e570fe0 722 ORDER BY w.state, w.email, a.alias";
723 $it = Xdb::iterRow($sql);
724
725 $table = array();
726 $props = array();
727 while (list($email, $date, $state, $forlife) = $it->next()) {
728 if (count($props) == 0 || $props['mail'] != $email) {
729 if (count($props) > 0) {
730 $table[] = $props;
731 }
732 $props = array('mail' => $email,
733 'detection' => $date,
734 'state' => $state,
735 'users' => array($forlife));
736 } else {
737 $props['users'][] = $forlife;
738 }
739 }
740 if (count($props) > 0) {
741 $table[] = $props;
742 }
743 $page->assign('table', $table);
744 } elseif ($action == 'edit') {
745 $sql = "SELECT w.detection, w.state, w.last, w.description,
746 a1.alias AS edit, a2.alias AS forlife
747 FROM emails_watch AS w
eaf30d86 748 LEFT JOIN aliases AS a1 ON (a1.id = w.uid AND a1.type = 'a_vie')
9615c895 749 LEFT JOIN emails AS e ON (w.email = e.email)
ca6d07f4 750 LEFT JOIN aliases AS a2 ON (a2.id = e.uid AND a2.type = 'a_vie')
9e570fe0 751 WHERE w.email = {?}
752 ORDER BY a2.alias";
753 $it = Xdb::iterRow($sql, $email);
754
755 $props = array();
756 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
757 if (count($props) == 0) {
758 $props = array('mail' => $email,
759 'detection' => $detection,
760 'state' => $state,
761 'last' => $last,
762 'description' => $description,
763 'edit' => $edit,
764 'users' => array($forlife));
765 } else {
766 $props['users'][] = $forlife;
767 }
768 }
769 $page->assign('doublon', $props);
770 }
771 }
d4b25d1a 772
7727ffc7 773 function handler_lost(&$page, $action = 'list', $email = null)
774 {
775 $page->changeTpl('emails/lost.tpl');
eaf30d86 776
d4b25d1a
FB
777 // TODO: Order by promo.
778 $page->assign('lost_emails',
779 XDB::iterator("SELECT a.uid, a.hruid
780 FROM accounts AS a
781 INNER JOIN email_options AS eo ON (eo.uid = a.uid)
782 LEFT JOIN emails AS e ON (a.uid = e.uid AND FIND_IN_SET('active', e.flags))
783 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', eo.storage) = 0 AND
784 a.state = 'active'
785 ORDER BY a.hruid"));
7727ffc7 786 }
81b5b746 787}
788
a7de4ef7 789// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 790?>