Port emails/broken.
[platal.git] / modules / email.php
CommitLineData
81b5b746 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 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(
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),
62ce6356 33 'emails/antispam/submit' => $this->make_hook('submit', AUTH_COOKIE),
9c0a8f8c 34 'emails/test' => $this->make_hook('test', AUTH_COOKIE, 'user', NO_AUTH),
9e570fe0 35
3d17e48f
FB
36 'emails/rewrite/in' => $this->make_hook('rewrite_in', AUTH_PUBLIC),
37 'emails/rewrite/out' => $this->make_hook('rewrite_out', AUTH_PUBLIC),
38
2ee43273
FB
39 'emails/imap/in' => $this->make_hook('imap_in', AUTH_PUBLIC),
40
7727ffc7 41 'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
f141945d 42 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
5ff3f06b 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.
81b5b746 229 if ($action == 'remove' && $email) {
b7582015 230 $retour = $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 }
256 $retour = $redirect->add_email($new_email);
257 if ($retour == ERROR_INVALID_EMAIL) {
258 $page->assign('email', $new_email);
259 }
260 $page->assign('retour', $retour);
81b5b746 261 } elseif (empty($actifs)) {
44b071c2 262 $retour = ERROR_INACTIVE_REDIRECTION;
81b5b746 263 } elseif (is_array($actifs)) {
44b071c2 264 $retour = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
81b5b746 265 }
266 }
267
44b071c2
SJ
268 switch ($retour) {
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
304 WHERE id={?} 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
12a587df 325 $bogo = new Bogo(S::user());
b7582015 326 if (isset($statut_filtre)) {
11ed26e5 327 $bogo->change($statut_filtre + 0);
81b5b746 328 }
2d997414 329 $page->assign('filtre', $bogo->level());
81b5b746 330 }
331
62ce6356 332 function handler_submit(&$page)
333 {
8f201b69
FB
334 $wp = new PlWikiPage('Xorg.Mails');
335 $wp->buildCache();
62ce6356 336 $page->changeTpl('emails/submit_spam.tpl');
337
40d428d8
VZ
338 if (Post::has('send_email')) {
339 S::assert_xsrf_token();
340
f3df6d38 341 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
15603084 342 if (!$upload) {
a7d35093 343 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
62ce6356 344 return;
345 }
15603084 346 $mime = $upload->contentType();
62ce6356 347 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
15603084 348 $upload->clear();
faefdbb7 349 $page->trigError('Le fichier ne contient pas un email complet');
62ce6356 350 return;
351 }
2d997414
VZ
352 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
353
62ce6356 354 global $globals;
2d997414 355 $box = $type . '@' . $globals->mail->domain;
62ce6356 356 $mailer = new PlMailer();
357 $mailer->addTo($box);
2d997414
VZ
358 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
359 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
360 $mailer->addUploadAttachment($upload, $type . '.mail');
62ce6356 361 $mailer->send();
a7d35093 362 $page->trigSuccess('Le message a été transmis à ' . $box);
15603084 363 $upload->clear();
62ce6356 364 }
365 }
366
81b5b746 367 function handler_send(&$page)
368 {
81b5b746 369 $page->changeTpl('emails/send.tpl');
da419622 370 $page->addJsLink('ajax.js');
81b5b746 371
46f272fe 372 $page->setTitle('Envoyer un email');
81b5b746 373
374 // action si on recoit un formulaire
3360c04f 375 if (Post::has('save')) {
46504fb3
VZ
376 if (!S::has_xsrf_token()) {
377 return PL_FORBIDDEN;
378 }
379
3360c04f
FB
380 unset($_POST['save']);
381 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
382 $_POST['to_contacts'] = explode(';', @$_POST['to_contacts']);
383 $_POST['cc_contacts'] = explode(';', @$_POST['cc_contacts']);
384 $data = serialize($_POST);
385 XDB::execute("REPLACE INTO email_send_save
386 VALUES ({?}, {?})", S::i('uid'), $data);
387 }
388 exit;
40d428d8
VZ
389 } else if (Env::v('submit') == 'Envoyer') {
390 S::assert_xsrf_token();
391
91a14f73 392 function getEmails($aliases)
393 {
394 if (!is_array($aliases)) {
395 return null;
396 }
397 $rel = Env::v('contacts');
398 $ret = array();
399 foreach ($aliases as $alias) {
400 $ret[$alias] = $rel[$alias];
401 }
402 return join(', ', $ret);
403 }
404
5e68682e 405 $error = false;
da419622 406 foreach ($_FILES as &$file) {
f3df6d38 407 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 408 $page->trigError(PlUpload::$lastError);
5e68682e
FB
409 $error = true;
410 break;
da419622 411 }
412 }
413
5e68682e
FB
414 if (!$error) {
415 XDB::execute("DELETE FROM email_send_save
416 WHERE uid = {?}", S::i('uid'));
417
418 $to2 = getEmails(Env::v('to_contacts'));
419 $cc2 = getEmails(Env::v('cc_contacts'));
420 $txt = str_replace('^M', '', Env::v('contenu'));
421 $to = Env::v('to');
422 $subj = Env::v('sujet');
423 $from = Env::v('from');
424 $cc = trim(Env::v('cc'));
425 $bcc = trim(Env::v('bcc'));
426
427 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 428 $page->trigError("Indique au moins un destinataire.");
f3df6d38 429 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
430 } else {
431 $mymail = new PlMailer();
432 $mymail->setFrom($from);
433 $mymail->setSubject($subj);
434 if (!empty($to)) { $mymail->addTo($to); }
435 if (!empty($cc)) { $mymail->addCc($cc); }
436 if (!empty($bcc)) { $mymail->addBcc($bcc); }
437 if (!empty($to2)) { $mymail->addTo($to2); }
438 if (!empty($cc2)) { $mymail->addCc($cc2); }
f3df6d38 439 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
440 foreach ($files as $name=>&$upload) {
441 $mymail->addUploadAttachment($upload, $name);
442 }
443 if (Env::v('nowiki')) {
444 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
445 } else {
446 $mymail->setWikiBody($txt);
447 }
448 if ($mymail->send()) {
faefdbb7 449 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 450 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 451 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 452 } else {
a7d35093 453 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 454 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 455 }
81b5b746 456 }
457 }
458 } else {
3360c04f
FB
459 $res = XDB::query("SELECT data
460 FROM email_send_save
461 WHERE uid = {?}", S::i('uid'));
462 if ($res->numRows() == 0) {
f3df6d38 463 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 464 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
465 } else {
466 $data = unserialize($res->fetchOneCell());
467 $_REQUEST = array_merge($_REQUEST, $data);
468 }
81b5b746 469 }
470
08cce2ff 471 $res = XDB::query(
57a29e19
FB
472 "SELECT ac.full_name, a.alias as forlife
473 FROM accounts AS ac
474 INNER JOIN contacts AS c ON (ac.uid = c.contact)
475 INNER JOIN aliases AS a ON (ac.uid = a.id AND FIND_IN_SET('bestalias', a.flags))
81b5b746 476 WHERE c.uid = {?}
57a29e19 477 ORDER BY ac.full_name", S::i('uid'));
81b5b746 478 $page->assign('contacts', $res->fetchAllAssoc());
5e68682e 479 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 480 $page->assign('user', S::user());
81b5b746 481 }
482
d0c3e04d 483 function handler_test(&$page, $hruid = null)
5ff3f06b 484 {
e4ecada4
VZ
485 require_once 'emails.inc.php';
486
46504fb3
VZ
487 if (!S::has_xsrf_token()) {
488 return PL_FORBIDDEN;
489 }
d0c3e04d
VZ
490
491 // Retrieves the User object for the test email recipient.
492 if (S::has_perms() && $hruid) {
493 $user = User::getSilent($hruid);
494 } else {
495 $user = S::user();
496 }
497 if (!$user) {
498 return PL_NOT_FOUND;
5ff3f06b 499 }
e4ecada4 500
d0c3e04d 501 // Sends the test email.
12a587df 502 $redirect = new Redirect($user);
e4ecada4
VZ
503
504 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 505 $mailer->assign('email', $user->bestEmail());
e4ecada4 506 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
507 $mailer->assign('display_name', $user->displayName());
508 $mailer->assign('sexe', $user->isFemale());
509 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
510 exit;
511 }
512
3d17e48f
FB
513 function handler_rewrite_in(&$page, $mail, $hash)
514 {
515 $page->changeTpl('emails/rewrite.tpl');
516 $page->assign('option', 'in');
517 if (empty($mail) || empty($hash)) {
518 return PL_NOT_FOUND;
519 }
520 $pos = strrpos($mail, '_');
521 if ($pos === false) {
522 return PL_NOT_FOUND;
523 }
524 $mail{$pos} = '@';
525 $res = XDB::query("SELECT COUNT(*)
526 FROM emails
527 WHERE email = {?} AND hash = {?}",
528 $mail, $hash);
529 $count = intval($res->fetchOneCell());
530 if ($count > 0) {
531 XDB::query("UPDATE emails
532 SET allow_rewrite = true, hash = NULL
533 WHERE email = {?} AND hash = {?}",
534 $mail, $hash);
535 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
536 return;
537 }
538 return PL_NOT_FOUND;
539 }
540
541 function handler_rewrite_out(&$page, $mail, $hash)
542 {
543 $page->changeTpl('emails/rewrite.tpl');
544 $page->assign('option', 'out');
545 if (empty($mail) || empty($hash)) {
546 return PL_NOT_FOUND;
547 }
548 $pos = strrpos($mail, '_');
549 if ($pos === false) {
550 return PL_NOT_FOUND;
551 }
552 $mail{$pos} = '@';
553 $res = XDB::query("SELECT COUNT(*)
554 FROM emails
555 WHERE email = {?} AND hash = {?}",
556 $mail, $hash);
557 $count = intval($res->fetchOneCell());
558 if ($count > 0) {
559 global $globals;
560 $res = XDB::query("SELECT e.email, e.rewrite, a.alias
561 FROM emails AS e
562 INNER JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
563 WHERE e.email = {?} AND e.hash = {?}",
564 $mail, $hash);
565 XDB::query("UPDATE emails
566 SET allow_rewrite = false, hash = NULL
567 WHERE email = {?} AND hash = {?}",
568 $mail, $hash);
569 list($mail, $rewrite, $forlife) = $res->fetchOneRow();
570 $mail = new PlMailer();
571 $mail->setFrom("webmaster@" . $globals->mail->domain);
572 $mail->addTo("support@" . $globals->mail->domain);
573 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
574 $mail->setTxtBody("$forlife a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
575 $mail->send();
576 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
577 return;
578 }
579 return PL_NOT_FOUND;
580 }
581
2ee43273
FB
582 function handler_imap_in(&$page, $hash = null, $login = null)
583 {
584 $page->changeTpl('emails/imap_register.tpl');
12a587df 585 $user = null;
2ee43273 586 if (!empty($hash) || !empty($login)) {
12a587df
VZ
587 $user = User::getSilent($login);
588 if ($user) {
589 $req = XDB::query("SELECT 1 FROM newsletter_ins WHERE user_id = {?} AND hash = {?}", $user->id(), $hash);
590 if ($req->numRows() == 0) {
591 $user = null;
592 }
593 }
2ee43273
FB
594 }
595
596 require_once('emails.inc.php');
597 $page->assign('ok', false);
12a587df
VZ
598 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
599 $storage = new EmailStorage(S::user(), 'imap');
2ee43273
FB
600 $storage->activate();
601 $page->assign('ok', true);
602 $page->assign('prenom', S::v('prenom'));
e2cea47d 603 $page->assign('sexe', S::v('femme'));
12a587df
VZ
604 } else if (!S::logged() && $user) {
605 $storage = new EmailStorage($user, 'imap');
2ee43273
FB
606 $storage->activate();
607 $page->assign('ok', true);
12a587df
VZ
608 $page->assign('prenom', $user->displayName());
609 $page->assign('sexe', $user->isFemale());
2ee43273
FB
610 }
611 }
612
81b5b746 613 function handler_broken(&$page, $warn = null, $email = null)
614 {
615 require_once 'emails.inc.php';
8f201b69
FB
616 $wp = new PlWikiPage('Xorg.PatteCassée');
617 $wp->buildCache();
81b5b746 618
619 global $globals;
620
621 $page->changeTpl('emails/broken.tpl');
622
40d428d8 623 if ($warn == 'warn' && $email) {
2c93e70e 624 //S::assert_xsrf_token();
40d428d8 625
81b5b746 626 $email = valide_email($email);
a7de4ef7 627 // vérifications d'usage
2c93e70e
FB
628 $uid = XDB::fetchOneCell("SELECT uid
629 FROM emails
630 WHERE email = {?}", $email);
631 if ($uid) {
632 $dest = User::getWithUID($uid);
633
634 $mail = new PlMailer('emails/broken-web.mail.tpl');
635 $mail->assign('email', $email);
636 $mail->assign('request', S::user());
637 $mail->sendTo($dest);
faefdbb7 638 $page->trigSuccess("Email envoyé !");
81b5b746 639 }
40d428d8
VZ
640 } elseif (Post::has('email')) {
641 S::assert_xsrf_token();
642
5e2307dc 643 $email = valide_email(Post::v('email'));
81b5b746 644
645 list(,$fqdn) = explode('@', $email);
646 $fqdn = strtolower($fqdn);
40d428d8 647 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
81b5b746 648 $page->assign('neuneu', true);
649 } else {
650 $page->assign('email',$email);
2c93e70e
FB
651 $x = XDB::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne,
652 (count(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
653 FROM emails as e1
654 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
655 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
81b5b746 656 AND FIND_IN_SET('active', e2.flags)
657 AND e1.email != e2.email)
2c93e70e
FB
658 WHERE e1.email = {?}
659 GROUP BY e1.uid", $email);
660 if ($x) {
a7de4ef7 661 // on écrit dans la base que l'adresse est cassée
81b5b746 662 if (!$x['panne']) {
2c93e70e
FB
663 XDB::execute("UPDATE emails
664 SET panne=NOW(), last=NOW(), panne_level = 1
665 WHERE email = {?}", $email);
74938c82 666 } else {
2c93e70e
FB
667 XDB::execute("UPDATE emails
668 SET panne_level = 1
669 WHERE email = {?} AND panne_level = 0", $email);
81b5b746 670 }
2c93e70e 671 $x['user'] = User::getWithUID($x['uid']);
81b5b746 672 $page->assign_by_ref('x', $x);
673 }
674 }
675 }
676 }
9e570fe0 677
678 function handler_duplicated(&$page, $action = 'list', $email = null)
679 {
680 $page->changeTpl('emails/duplicated.tpl');
681
682 $states = array('pending' => 'En attente...',
a7de4ef7 683 'safe' => 'Pas d\'inquiétude',
9e570fe0 684 'unsafe' => 'Recherches en cours',
685 'dangerous' => 'Usurpations par cette adresse');
686 $page->assign('states', $states);
687
40d428d8
VZ
688 if (Post::has('action')) {
689 S::assert_xsrf_token();
46504fb3 690 }
9e570fe0 691 switch (Post::v('action')) {
46504fb3 692 case 'create':
9e570fe0 693 if (trim(Post::v('emailN')) != '') {
694 Xdb::execute('INSERT IGNORE INTO emails_watch (email, state, detection, last, uid, description)
695 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
696 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
697 };
698 break;
699
46504fb3 700 case 'edit':
9e570fe0 701 Xdb::execute('UPDATE emails_watch
702 SET state = {?}, last = NOW(), uid = {?}, description = {?}
703 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
704 break;
705
46504fb3 706 default:
9e570fe0 707 if ($action == 'delete' && !is_null($email)) {
708 Xdb::execute('DELETE FROM emails_watch WHERE email = {?}', $email);
709 }
710 }
711 if ($action != 'create' && $action != 'edit') {
712 $action = 'list';
713 }
714 $page->assign('action', $action);
715
716 if ($action == 'list') {
717 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
718 FROM emails_watch AS w
ca6d07f4 719 LEFT JOIN emails AS e USING(email)
720 LEFT JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
9e570fe0 721 ORDER BY w.state, w.email, a.alias";
722 $it = Xdb::iterRow($sql);
723
724 $table = array();
725 $props = array();
726 while (list($email, $date, $state, $forlife) = $it->next()) {
727 if (count($props) == 0 || $props['mail'] != $email) {
728 if (count($props) > 0) {
729 $table[] = $props;
730 }
731 $props = array('mail' => $email,
732 'detection' => $date,
733 'state' => $state,
734 'users' => array($forlife));
735 } else {
736 $props['users'][] = $forlife;
737 }
738 }
739 if (count($props) > 0) {
740 $table[] = $props;
741 }
742 $page->assign('table', $table);
743 } elseif ($action == 'edit') {
744 $sql = "SELECT w.detection, w.state, w.last, w.description,
745 a1.alias AS edit, a2.alias AS forlife
746 FROM emails_watch AS w
eaf30d86 747 LEFT JOIN aliases AS a1 ON (a1.id = w.uid AND a1.type = 'a_vie')
9615c895 748 LEFT JOIN emails AS e ON (w.email = e.email)
ca6d07f4 749 LEFT JOIN aliases AS a2 ON (a2.id = e.uid AND a2.type = 'a_vie')
9e570fe0 750 WHERE w.email = {?}
751 ORDER BY a2.alias";
752 $it = Xdb::iterRow($sql, $email);
753
754 $props = array();
755 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
756 if (count($props) == 0) {
757 $props = array('mail' => $email,
758 'detection' => $detection,
759 'state' => $state,
760 'last' => $last,
761 'description' => $description,
762 'edit' => $edit,
763 'users' => array($forlife));
764 } else {
765 $props['users'][] = $forlife;
766 }
767 }
768 $page->assign('doublon', $props);
769 }
770 }
7727ffc7 771 function handler_lost(&$page, $action = 'list', $email = null)
772 {
773 $page->changeTpl('emails/lost.tpl');
eaf30d86 774
2d997414
VZ
775 $page->assign('lost_emails', XDB::iterator("
776 SELECT u.user_id, u.hruid
0e5ec860 777 FROM auth_user_md5 AS u
2d997414
VZ
778 LEFT JOIN emails AS e ON (u.user_id = e.uid AND FIND_IN_SET('active', e.flags))
779 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', u.mail_storage) = 0 AND
780 u.deces = 0 AND u.perms IN ('user', 'admin', 'disabled')
781 ORDER BY u.promo DESC, u.nom, u.prenom"));
7727ffc7 782 }
81b5b746 783}
784
a7de4ef7 785// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 786?>