Merge commit 'origin/master' into hruid
[platal.git] / modules / email.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2008 Polytechnique.org *
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
22 class EmailModule extends PLModule
23 {
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),
33 'emails/antispam/submit' => $this->make_hook('submit', AUTH_COOKIE),
34 'emails/test' => $this->make_hook('test', AUTH_COOKIE, 'user', NO_AUTH),
35
36 'emails/imap/in' => $this->make_hook('imap_in', AUTH_PUBLIC),
37
38 'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
39 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
40 'admin/emails/lost' => $this->make_hook('lost', AUTH_MDP, 'admin'),
41 );
42 }
43
44 function handler_emails(&$page, $action = null, $email = null)
45 {
46 global $globals;
47 require_once 'emails.inc.php';
48
49 $page->changeTpl('emails/index.tpl');
50 $page->setTitle('Mes emails');
51
52 $user = S::user();
53
54 // Apply the bestalias change request.
55 if ($action == 'best' && $email) {
56 if (!S::has_xsrf_token()) {
57 return PL_FORBIDDEN;
58 }
59
60 XDB::execute("UPDATE aliases
61 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
62 WHERE id = {?}", $user->id());
63 XDB::execute("UPDATE aliases
64 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
65 WHERE id = {?} AND alias = {?}", $user->id(), $email);
66
67 // As having a non-null bestalias value is critical in
68 // plat/al's code, we do an a posteriori check on the
69 // validity of the bestalias.
70 fix_bestalias($user);
71 }
72
73 // Fetch and display aliases.
74 $sql = "SELECT alias, (type='a_vie') AS a_vie,
75 (alias REGEXP '\\\\.[0-9]{2}$') AS cent_ans,
76 FIND_IN_SET('bestalias',flags) AS best, expire
77 FROM aliases
78 WHERE id = {?} AND type!='homonyme'
79 ORDER BY LENGTH(alias)";
80 $page->assign('aliases', XDB::iterator($sql, $user->id()));
81
82 // Check for homonyms.
83 $homonyme = XDB::query(
84 "SELECT alias
85 FROM aliases
86 INNER JOIN homonymes ON (id = homonyme_id)
87 WHERE user_id = {?} AND type = 'homonyme'", $user->id());
88 $page->assign('homonyme', $homonyme->fetchOneCell());
89
90 // Display active redirections.
91 $redirect = new Redirect($user);
92 $page->assign('mails', $redirect->active_emails());
93
94 // Display, when available, the @alias_dom email alias.
95 $res = XDB::query(
96 "SELECT alias
97 FROM virtual AS v
98 INNER JOIN virtual_redirect AS vr USING(vid)
99 WHERE (redirect={?} OR redirect={?})
100 AND alias LIKE '%@{$globals->mail->alias_dom}'",
101 $user->forlifeEmail(),
102 // TODO: remove this über-ugly hack. The issue is that you need
103 // to remove all @m4x.org addresses in virtual_redirect first.
104 $user->login() . '@' . $globals->mail->domain2);
105 $page->assign('melix', $res->fetchOneCell());
106 }
107
108 function handler_alias(&$page, $action = null, $value = null)
109 {
110 require_once 'validations.inc.php';
111
112 global $globals;
113
114 $page->changeTpl('emails/alias.tpl');
115 $page->setTitle('Alias melix.net');
116
117 $user = S::user();
118 $page->assign('demande', AliasReq::get_request($user->id()));
119
120 // Remove the email alias.
121 if ($action == 'delete' && $value) {
122 S::assert_xsrf_token();
123
124 XDB::execute(
125 "DELETE virtual, virtual_redirect
126 FROM virtual
127 INNER JOIN virtual_redirect USING (vid)
128 WHERE alias = {?} AND (redirect = {?} OR redirect = {?})",
129 $value, $user->forlifeEmail(),
130 // TODO: remove this über-ugly hack. The issue is that you need
131 // to remove all @m4x.org addresses in virtual_redirect first.
132 $user->login() . '@' . $globals->mail->domain2);
133 }
134
135 // Fetch existing @alias_dom aliases.
136 $res = XDB::query(
137 "SELECT alias, emails_alias_pub
138 FROM auth_user_quick, virtual
139 INNER JOIN virtual_redirect USING(vid)
140 WHERE (redirect = {?} OR redirect = {?})
141 AND alias LIKE '%@{$globals->mail->alias_dom}' AND user_id = {?}",
142 $user->forlifeEmail(),
143 // TODO: remove this über-ugly hack. The issue is that you need
144 // to remove all @m4x.org addresses in virtual_redirect first.
145 $user->login() . '@' . $globals->mail->domain2, $user->id());
146 list($alias, $visibility) = $res->fetchOneRow();
147 $page->assign('actuel', $alias);
148
149 if ($action == 'ask' && Env::has('alias') && Env::has('raison')) {
150 S::assert_xsrf_token();
151
152 //Si l'utilisateur vient de faire une damande
153 $alias = Env::v('alias');
154 $raison = Env::v('raison');
155 $public = (Env::v('public', 'off') == 'on')?"public":"private";
156
157 $page->assign('r_alias', $alias);
158 $page->assign('r_raison', $raison);
159 if ($public == 'public') {
160 $page->assign('r_public', true);
161 }
162
163 //Quelques vérifications sur l'alias (caractères spéciaux)
164 if (!preg_match( "/^[a-zA-Z0-9\-.]{3,20}$/", $alias)) {
165 $page->trigError("L'adresse demandée n'est pas valide."
166 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
167 . " et qu'elle ne contient que des lettres non accentuées,"
168 . " des chiffres ou les caractères - et .");
169 return;
170 } else {
171 //vérifier que l'alias n'est pas déja pris
172 $res = XDB::query('SELECT COUNT(*) FROM virtual WHERE alias={?}',
173 $alias.'@'.$globals->mail->alias_dom);
174 if ($res->fetchOneCell() > 0) {
175 $page->trigError("L'alias $alias@{$globals->mail->alias_dom} a déja été attribué.
176 Tu ne peux donc pas l'obtenir.");
177 return;
178 }
179
180 //vérifier que l'alias n'est pas déja en demande
181 $it = new ValidateIterator ();
182 while($req = $it->next()) {
183 if ($req->type == "alias" and $req->alias == $alias . '@' . $globals->mail->alias_dom) {
184 $page->trigError("L'alias $alias@{$globals->mail->alias_dom} a déja été demandé.
185 Tu ne peux donc pas l'obtenir pour l'instant.");
186 return ;
187 }
188 }
189
190 //Insertion de la demande dans la base, écrase les requêtes précédente
191 $myalias = new AliasReq($user, $alias, $raison, $public);
192 $myalias->submit();
193 $page->assign('success',$alias);
194 return;
195 }
196 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
197 if (!S::has_xsrf_token()) {
198 return PL_FORBIDDEN;
199 }
200
201 if ($value == 'public') {
202 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'public'
203 WHERE user_id = {?}", $user->id());
204 } else {
205 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'private'
206 WHERE user_id = {?}", $user->id());
207 }
208
209 $visibility = $value;
210 }
211
212 $page->assign('mail_public', ($visibility == 'public'));
213 }
214
215 function handler_redirect(&$page, $action = null, $email = null)
216 {
217 global $globals;
218
219 require_once 'emails.inc.php';
220
221 $page->changeTpl('emails/redirect.tpl');
222
223 $user = S::user();
224 $page->assign_by_ref('user', $user);
225 $page->assign('eleve', $user->promo() >= date("Y") - 5);
226
227 $redirect = new Redirect($user);
228
229 // FS#703 : $_GET is urldecoded twice, hence
230 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
231 // Since there can be no spaces in emails, we can fix this with :
232 $email = str_replace(' ', '+', $email);
233
234 // Apply email redirection change requests.
235 if ($action == 'remove' && $email) {
236 $retour = $redirect->delete_email($email);
237 $page->assign('retour', $retour);
238 }
239
240 if ($action == 'active' && $email) {
241 $redirect->modify_one_email($email, true);
242 }
243
244 if ($action == 'inactive' && $email) {
245 $redirect->modify_one_email($email, false);
246 }
247
248 if ($action == 'rewrite' && $email) {
249 $rewrite = @func_get_arg(3);
250 $redirect->modify_one_email_redirect($email, $rewrite);
251 }
252
253 if (Env::has('emailop')) {
254 S::assert_xsrf_token();
255
256 $actifs = Env::v('emails_actifs', Array());
257 print_r(Env::v('emails_rewrite'));
258 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
259 $page->assign('retour', $redirect->add_email(Env::v('email')));
260 } elseif (empty($actifs)) {
261 $page->assign('retour', ERROR_INACTIVE_REDIRECTION);
262 } elseif (is_array($actifs)) {
263 $page->assign('retour', $redirect->modify_email($actifs,
264 Env::v('emails_rewrite',Array())));
265 }
266 }
267
268 // Fetch the @alias_dom email alias, if any.
269 $res = XDB::query(
270 "SELECT alias
271 FROM virtual
272 INNER JOIN virtual_redirect USING(vid)
273 WHERE (redirect={?} OR redirect={?})
274 AND alias LIKE '%@{$globals->mail->alias_dom}'",
275 $user->forlifeEmail(),
276 // TODO: remove this über-ugly hack. The issue is that you need
277 // to remove all @m4x.org addresses in virtual_redirect first.
278 $user->login() . '@' . $globals->mail->domain2);
279 $melix = $res->fetchOneCell();
280 if ($melix) {
281 list($melix) = explode('@', $melix);
282 $page->assign('melix',$melix);
283 }
284
285 // Fetch existing email aliases.
286 $res = XDB::query(
287 "SELECT alias,expire
288 FROM aliases
289 WHERE id={?} AND (type='a_vie' OR type='alias')
290 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
291 $page->assign('alias', $res->fetchAllAssoc());
292 $page->assign('emails', $redirect->emails);
293
294 // Display GoogleApps acount information.
295 require_once 'googleapps.inc.php';
296 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
297 }
298
299 function handler_antispam(&$page, $statut_filtre = null)
300 {
301 require_once 'emails.inc.php';
302 $wp = new PlWikiPage('Xorg.Antispam');
303 $wp->buildCache();
304
305 $page->changeTpl('emails/antispam.tpl');
306
307 $bogo = new Bogo(S::user());
308 if (isset($statut_filtre)) {
309 $bogo->change($statut_filtre + 0);
310 }
311 $page->assign('filtre', $bogo->level());
312 }
313
314 function handler_submit(&$page)
315 {
316 $wp = new PlWikiPage('Xorg.Mails');
317 $wp->buildCache();
318 $page->changeTpl('emails/submit_spam.tpl');
319
320 if (Post::has('send_email')) {
321 S::assert_xsrf_token();
322
323 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
324 if (!$upload) {
325 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
326 return;
327 }
328 $mime = $upload->contentType();
329 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
330 $upload->clear();
331 $page->trigError('Le fichier ne contient pas un email complet');
332 return;
333 }
334 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
335
336 global $globals;
337 $box = $type . '@' . $globals->mail->domain;
338 $mailer = new PlMailer();
339 $mailer->addTo($box);
340 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
341 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
342 $mailer->addUploadAttachment($upload, $type . '.mail');
343 $mailer->send();
344 $page->trigSuccess('Le message a été transmis à ' . $box);
345 $upload->clear();
346 }
347 }
348
349 function handler_send(&$page)
350 {
351 $page->changeTpl('emails/send.tpl');
352 $page->addJsLink('ajax.js');
353
354 $page->setTitle('Envoyer un email');
355
356 // action si on recoit un formulaire
357 if (Post::has('save')) {
358 if (!S::has_xsrf_token()) {
359 return PL_FORBIDDEN;
360 }
361
362 unset($_POST['save']);
363 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
364 $_POST['to_contacts'] = explode(';', @$_POST['to_contacts']);
365 $_POST['cc_contacts'] = explode(';', @$_POST['cc_contacts']);
366 $data = serialize($_POST);
367 XDB::execute("REPLACE INTO email_send_save
368 VALUES ({?}, {?})", S::i('uid'), $data);
369 }
370 exit;
371 } else if (Env::v('submit') == 'Envoyer') {
372 S::assert_xsrf_token();
373
374 function getEmails($aliases)
375 {
376 if (!is_array($aliases)) {
377 return null;
378 }
379 $rel = Env::v('contacts');
380 $ret = array();
381 foreach ($aliases as $alias) {
382 $ret[$alias] = $rel[$alias];
383 }
384 return join(', ', $ret);
385 }
386
387 $error = false;
388 foreach ($_FILES as &$file) {
389 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
390 $page->trigError(PlUpload::$lastError);
391 $error = true;
392 break;
393 }
394 }
395
396 if (!$error) {
397 XDB::execute("DELETE FROM email_send_save
398 WHERE uid = {?}", S::i('uid'));
399
400 $to2 = getEmails(Env::v('to_contacts'));
401 $cc2 = getEmails(Env::v('cc_contacts'));
402 $txt = str_replace('^M', '', Env::v('contenu'));
403 $to = Env::v('to');
404 $subj = Env::v('sujet');
405 $from = Env::v('from');
406 $cc = trim(Env::v('cc'));
407 $bcc = trim(Env::v('bcc'));
408
409 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
410 $page->trigError("Indique au moins un destinataire.");
411 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
412 } else {
413 $mymail = new PlMailer();
414 $mymail->setFrom($from);
415 $mymail->setSubject($subj);
416 if (!empty($to)) { $mymail->addTo($to); }
417 if (!empty($cc)) { $mymail->addCc($cc); }
418 if (!empty($bcc)) { $mymail->addBcc($bcc); }
419 if (!empty($to2)) { $mymail->addTo($to2); }
420 if (!empty($cc2)) { $mymail->addCc($cc2); }
421 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
422 foreach ($files as $name=>&$upload) {
423 $mymail->addUploadAttachment($upload, $name);
424 }
425 if (Env::v('nowiki')) {
426 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
427 } else {
428 $mymail->setWikiBody($txt);
429 }
430 if ($mymail->send()) {
431 $page->trigSuccess("Ton email a bien été envoyé.");
432 $_REQUEST = array('bcc' => S::user()->bestEmail());
433 PlUpload::clear(S::user()->login(), 'emails.send');
434 } else {
435 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
436 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
437 }
438 }
439 }
440 } else {
441 $res = XDB::query("SELECT data
442 FROM email_send_save
443 WHERE uid = {?}", S::i('uid'));
444 if ($res->numRows() == 0) {
445 PlUpload::clear(S::user()->login(), 'emails.send');
446 $_REQUEST['bcc'] = S::user()->bestEmail();
447 } else {
448 $data = unserialize($res->fetchOneCell());
449 $_REQUEST = array_merge($_REQUEST, $data);
450 }
451 }
452
453 $res = XDB::query(
454 "SELECT u.prenom, u.nom, u.promo, a.alias as forlife
455 FROM auth_user_md5 AS u
456 INNER JOIN contacts AS c ON (u.user_id = c.contact)
457 INNER JOIN aliases AS a ON (u.user_id=a.id AND FIND_IN_SET('bestalias',a.flags))
458 WHERE c.uid = {?}
459 ORDER BY u.nom, u.prenom", S::v('uid'));
460 $page->assign('contacts', $res->fetchAllAssoc());
461 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
462 $page->assign('user', S::user());
463 }
464
465 function handler_test(&$page, $hruid = null)
466 {
467 require_once 'emails.inc.php';
468
469 if (!S::has_xsrf_token()) {
470 return PL_FORBIDDEN;
471 }
472
473 // Retrieves the User object for the test email recipient.
474 if (S::has_perms() && $hruid) {
475 $user = User::getSilent($hruid);
476 } else {
477 $user = S::user();
478 }
479 if (!$user) {
480 return PL_NOT_FOUND;
481 }
482
483 // Sends the test email.
484 $redirect = new Redirect($user);
485
486 $mailer = new PlMailer('emails/test.mail.tpl');
487 $mailer->assign('email', $user->bestEmail());
488 $mailer->assign('redirects', $redirect->active_emails());
489 $mailer->assign('display_name', $user->displayName());
490 $mailer->assign('sexe', $user->isFemale());
491 $mailer->send($user->isEmailFormatHtml());
492 exit;
493 }
494
495 function handler_imap_in(&$page, $hash = null, $login = null)
496 {
497 $page->changeTpl('emails/imap_register.tpl');
498 $user = null;
499 if (!empty($hash) || !empty($login)) {
500 $user = User::getSilent($login);
501 if ($user) {
502 $req = XDB::query("SELECT 1 FROM newsletter_ins WHERE user_id = {?} AND hash = {?}", $user->id(), $hash);
503 if ($req->numRows() == 0) {
504 $user = null;
505 }
506 }
507 }
508
509 require_once('emails.inc.php');
510 $page->assign('ok', false);
511 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
512 $storage = new EmailStorage(S::user(), 'imap');
513 $storage->activate();
514 $page->assign('ok', true);
515 $page->assign('prenom', S::v('prenom'));
516 $page->assign('sexe', S::v('femme'));
517 } else if (!S::logged() && $user) {
518 $storage = new EmailStorage($user, 'imap');
519 $storage->activate();
520 $page->assign('ok', true);
521 $page->assign('prenom', $user->displayName());
522 $page->assign('sexe', $user->isFemale());
523 }
524 }
525
526 function handler_broken(&$page, $warn = null, $email = null)
527 {
528 require_once 'emails.inc.php';
529 $wp = new PlWikiPage('Xorg.PatteCassée');
530 $wp->buildCache();
531
532 global $globals;
533
534 $page->changeTpl('emails/broken.tpl');
535
536 if ($warn == 'warn' && $email) {
537 S::assert_xsrf_token();
538
539 $email = valide_email($email);
540 // vérifications d'usage
541 $sel = XDB::query("SELECT uid FROM emails WHERE email = {?}", $email);
542 if (($uid = $sel->fetchOneCell())) {
543 $dest = User::getSilent($uid);
544
545 // envoi du mail
546 $message = "Bonjour !
547
548 Cet email a été généré automatiquement par le service de patte cassée de
549 Polytechnique.org car un autre utilisateur, " . S::user()->fullName() . ",
550 nous a signalé qu'en t'envoyant un email, il avait reçu un message d'erreur
551 indiquant que ton adresse de redirection $email
552 ne fonctionnait plus !
553
554 Nous te suggérons de vérifier cette adresse, et le cas échéant de mettre
555 à jour sur le site <{$globals->baseurl}/emails> tes adresses
556 de redirection...
557
558 Pour plus de renseignements sur le service de patte cassée, n'hésite pas à
559 consulter la page <{$globals->baseurl}/emails/broken>.
560
561
562 À bientôt sur Polytechnique.org !
563 L'équipe d'administration <support@" . $globals->mail->domain . '>';
564
565 $mail = new PlMailer();
566 $mail->setFrom('"Polytechnique.org" <support@' . $globals->mail->domain . '>');
567 $mail->addTo($dest->bestEmail());
568 $mail->setSubject("Une de tes adresse de redirection Polytechnique.org ne marche plus !!");
569 $mail->setTxtBody($message);
570 $mail->send();
571 $page->trigSuccess("Email envoyé !");
572 }
573 } elseif (Post::has('email')) {
574 S::assert_xsrf_token();
575
576 $email = valide_email(Post::v('email'));
577
578 list(,$fqdn) = explode('@', $email);
579 $fqdn = strtolower($fqdn);
580 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
581 $page->assign('neuneu', true);
582 } else {
583 $page->assign('email',$email);
584 $sel = XDB::query(
585 "SELECT e1.uid, e1.panne != 0 AS panne,
586 (count(e2.uid) + IF(FIND_IN_SET('googleapps', u.mail_storage), 1, 0)) AS nb_mails,
587 u.nom, u.prenom, u.promo, u.hruid
588 FROM emails as e1
589 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
590 AND FIND_IN_SET('active', e2.flags)
591 AND e1.email != e2.email)
592 INNER JOIN auth_user_md5 as u ON(e1.uid = u.user_id)
593 WHERE e1.email = {?}
594 GROUP BY e1.uid", $email);
595 if ($x = $sel->fetchOneAssoc()) {
596 // on écrit dans la base que l'adresse est cassée
597 if (!$x['panne']) {
598 XDB::execute("UPDATE emails
599 SET panne=NOW(),
600 last=NOW(),
601 panne_level = 1
602 WHERE email = {?}", $email);
603 } else {
604 XDB::execute("UPDATE emails
605 SET panne_level = 1
606 WHERE email = {?} AND panne_level = 0", $email);
607 }
608 $page->assign_by_ref('x', $x);
609 }
610 }
611 }
612 }
613
614 function handler_duplicated(&$page, $action = 'list', $email = null)
615 {
616 $page->changeTpl('emails/duplicated.tpl');
617
618 $states = array('pending' => 'En attente...',
619 'safe' => 'Pas d\'inquiétude',
620 'unsafe' => 'Recherches en cours',
621 'dangerous' => 'Usurpations par cette adresse');
622 $page->assign('states', $states);
623
624 if (Post::has('action')) {
625 S::assert_xsrf_token();
626 }
627 switch (Post::v('action')) {
628 case 'create':
629 if (trim(Post::v('emailN')) != '') {
630 Xdb::execute('INSERT IGNORE INTO emails_watch (email, state, detection, last, uid, description)
631 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
632 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
633 };
634 break;
635
636 case 'edit':
637 Xdb::execute('UPDATE emails_watch
638 SET state = {?}, last = NOW(), uid = {?}, description = {?}
639 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
640 break;
641
642 default:
643 if ($action == 'delete' && !is_null($email)) {
644 Xdb::execute('DELETE FROM emails_watch WHERE email = {?}', $email);
645 }
646 }
647 if ($action != 'create' && $action != 'edit') {
648 $action = 'list';
649 }
650 $page->assign('action', $action);
651
652 if ($action == 'list') {
653 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
654 FROM emails_watch AS w
655 LEFT JOIN emails AS e USING(email)
656 LEFT JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
657 ORDER BY w.state, w.email, a.alias";
658 $it = Xdb::iterRow($sql);
659
660 $table = array();
661 $props = array();
662 while (list($email, $date, $state, $forlife) = $it->next()) {
663 if (count($props) == 0 || $props['mail'] != $email) {
664 if (count($props) > 0) {
665 $table[] = $props;
666 }
667 $props = array('mail' => $email,
668 'detection' => $date,
669 'state' => $state,
670 'users' => array($forlife));
671 } else {
672 $props['users'][] = $forlife;
673 }
674 }
675 if (count($props) > 0) {
676 $table[] = $props;
677 }
678 $page->assign('table', $table);
679 } elseif ($action == 'edit') {
680 $sql = "SELECT w.detection, w.state, w.last, w.description,
681 a1.alias AS edit, a2.alias AS forlife
682 FROM emails_watch AS w
683 LEFT JOIN aliases AS a1 ON (a1.id = w.uid AND a1.type = 'a_vie')
684 LEFT JOIN emails AS e ON (w.email = e.email)
685 LEFT JOIN aliases AS a2 ON (a2.id = e.uid AND a2.type = 'a_vie')
686 WHERE w.email = {?}
687 ORDER BY a2.alias";
688 $it = Xdb::iterRow($sql, $email);
689
690 $props = array();
691 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
692 if (count($props) == 0) {
693 $props = array('mail' => $email,
694 'detection' => $detection,
695 'state' => $state,
696 'last' => $last,
697 'description' => $description,
698 'edit' => $edit,
699 'users' => array($forlife));
700 } else {
701 $props['users'][] = $forlife;
702 }
703 }
704 $page->assign('doublon', $props);
705 }
706 }
707 function handler_lost(&$page, $action = 'list', $email = null)
708 {
709 $page->changeTpl('emails/lost.tpl');
710
711 $page->assign('lost_emails', XDB::iterator("
712 SELECT u.user_id, u.hruid
713 FROM auth_user_md5 AS u
714 LEFT JOIN emails AS e ON (u.user_id = e.uid AND FIND_IN_SET('active', e.flags))
715 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', u.mail_storage) = 0 AND
716 u.deces = 0 AND u.perms IN ('user', 'admin', 'disabled')
717 ORDER BY u.promo DESC, u.nom, u.prenom"));
718 }
719 }
720
721 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
722 ?>