Use PlUpload on the spam submission form
[platal.git] / modules / email.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 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
35 'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
36 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
37 'admin/emails/lost' => $this->make_hook('lost', AUTH_MDP, 'admin'),
38 );
39 }
40
41 function handler_emails(&$page, $action = null, $email = null)
42 {
43 global $globals;
44
45 $page->changeTpl('emails/index.tpl');
46 $page->assign('xorg_title','Polytechnique.org - Mes emails');
47
48 $uid = S::v('uid');
49
50 if ($action == 'best' && $email) {
51 // bestalias is the first bit : 1
52 // there will be maximum 8 bits in flags : 255
53 XDB::execute("UPDATE aliases SET flags=flags & (255 - 1) WHERE id={?}", $uid);
54 XDB::execute("UPDATE aliases SET flags=flags | 1 WHERE id={?} AND alias={?}",
55 $uid, $email);
56 }
57
58 // on regarde si on a affaire à un homonyme
59 $sql = "SELECT alias, (type='a_vie') AS a_vie,
60 (alias REGEXP '\\\\.[0-9]{2}$') AS cent_ans,
61 FIND_IN_SET('bestalias',flags) AS best, expire
62 FROM aliases
63 WHERE id = {?} AND type!='homonyme'
64 ORDER BY LENGTH(alias)";
65 $page->assign('aliases', XDB::iterator($sql, $uid));
66
67 $homonyme = XDB::query("SELECT alias FROM aliases INNER JOIN homonymes ON (id = homonyme_id) WHERE user_id = {?} AND type = 'homonyme'", $uid);
68 $page->assign('homonyme', $homonyme->fetchOneCell());
69
70 $sql = "SELECT email
71 FROM emails
72 WHERE uid = {?} AND FIND_IN_SET('active', flags)";
73 $page->assign('mails', XDB::iterator($sql, $uid));
74
75
76 // on regarde si l'utilisateur a un alias et si oui on l'affiche !
77 $forlife = S::v('forlife');
78 $res = XDB::query(
79 "SELECT alias
80 FROM virtual AS v
81 INNER JOIN virtual_redirect AS vr USING(vid)
82 WHERE (redirect={?} OR redirect={?})
83 AND alias LIKE '%@{$globals->mail->alias_dom}'",
84 $forlife.'@'.$globals->mail->domain, $forlife.'@'.$globals->mail->domain2);
85 $page->assign('melix', $res->fetchOneCell());
86 }
87
88 function handler_alias(&$page, $action = null, $value = null)
89 {
90 require_once 'validations.inc.php';
91
92 global $globals;
93
94 $page->changeTpl('emails/alias.tpl');
95 $page->assign('xorg_title','Polytechnique.org - Alias melix.net');
96
97 $uid = S::v('uid');
98 $forlife = S::v('forlife');
99
100 $page->assign('demande', AliasReq::get_request($uid));
101
102 if ($action == 'delete' && $value) {
103 //Suppression d'un alias
104 XDB::execute(
105 'DELETE virtual, virtual_redirect
106 FROM virtual
107 INNER JOIN virtual_redirect USING (vid)
108 WHERE alias = {?} AND (redirect = {?} OR redirect = {?})', $value,
109 $forlife.'@'.$globals->mail->domain, $forlife.'@'.$globals->mail->domain2);
110 }
111
112 //Récupération des alias éventuellement existants
113 $res = XDB::query(
114 "SELECT alias, emails_alias_pub
115 FROM auth_user_quick, virtual
116 INNER JOIN virtual_redirect USING(vid)
117 WHERE ( redirect={?} OR redirect= {?} )
118 AND alias LIKE '%@{$globals->mail->alias_dom}' AND user_id = {?}",
119 $forlife.'@'.$globals->mail->domain,
120 $forlife.'@'.$globals->mail->domain2, S::v('uid'));
121 list($alias, $visibility) = $res->fetchOneRow();
122 $page->assign('actuel', $alias);
123
124 if ($action == 'ask' && Env::has('alias') and Env::has('raison')) {
125 //Si l'utilisateur vient de faire une damande
126
127 $alias = Env::v('alias');
128 $raison = Env::v('raison');
129 $public = (Env::v('public', 'off') == 'on')?"public":"private";
130
131 $page->assign('r_alias', $alias);
132 $page->assign('r_raison', $raison);
133 if ($public == 'public') {
134 $page->assign('r_public', true);
135 }
136
137 //Quelques vérifications sur l'alias (caractères spéciaux)
138 if (!preg_match( "/^[a-zA-Z0-9\-.]{3,20}$/", $alias)) {
139 $page->trig("L'adresse demandée n'est pas valide.
140 Vérifie qu'elle comporte entre 3 et 20 caractères
141 et qu'elle ne contient que des lettres non accentuées,
142 des chiffres ou les caractères - et .");
143 return;
144 } else {
145 //vérifier que l'alias n'est pas déja pris
146 $res = XDB::query('SELECT COUNT(*) FROM virtual WHERE alias={?}',
147 $alias.'@'.$globals->mail->alias_dom);
148 if ($res->fetchOneCell() > 0) {
149 $page->trig("L'alias $alias@{$globals->mail->alias_dom} a déja été attribué.
150 Tu ne peux donc pas l'obtenir.");
151 return;
152 }
153
154 //vérifier que l'alias n'est pas déja en demande
155 $it = new ValidateIterator ();
156 while($req = $it->next()) {
157 if ($req->type == "alias" and $req->alias == $alias) {
158 $page->trig("L'alias $alias@{$globals->mail->alias_dom} a déja été demandé.
159 Tu ne peux donc pas l'obtenir pour l'instant.");
160 return ;
161 }
162 }
163
164 //Insertion de la demande dans la base, écrase les requêtes précédente
165 $myalias = new AliasReq($uid, $alias, $raison, $public);
166 $myalias->submit();
167 $page->assign('success',$alias);
168 return;
169 }
170 }
171 elseif ($action == 'set'
172 && ($value == 'public' || $value == 'private'))
173 {
174 if ($value == 'public') {
175 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'public'
176 WHERE user_id = {?}", S::v('uid'));
177 } else {
178 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'private'
179 WHERE user_id = {?}", S::v('uid'));
180 }
181
182 $visibility = $value;
183 }
184
185 $page->assign('mail_public', ($visibility == 'public'));
186 }
187
188 function handler_redirect(&$page, $action = null, $email = null)
189 {
190 global $globals;
191
192 require_once 'emails.inc.php';
193
194 $page->changeTpl('emails/redirect.tpl');
195
196 $uid = S::v('uid');
197 $forlife = S::v('forlife');
198
199 $page->assign('eleve', S::i('promo') >= date("Y") - 5);
200
201 $redirect = new Redirect(S::v('uid'));
202
203 if ($action == 'remove' && $email) {
204 $retour = $redirect->delete_email($email);
205 $page->assign('retour', $retour);
206 }
207
208 if ($action == 'active' && $email) {
209 $redirect->modify_one_email($email, true);
210 }
211
212 if ($action == 'inactive' && $email) {
213 $redirect->modify_one_email($email, false);
214 }
215
216 if ($action == 'rewrite' && $email) {
217 $rewrite = @func_get_arg(3);
218 $redirect->modify_one_email_redirect($email, $rewrite);
219 }
220
221 if (Env::has('emailop')) {
222 $actifs = Env::v('emails_actifs', Array());
223 print_r(Env::v('emails_rewrite'));
224 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
225 $page->assign('retour', $redirect->add_email(Env::v('email')));
226 } elseif (empty($actifs)) {
227 $page->assign('retour', ERROR_INACTIVE_REDIRECTION);
228 } elseif (is_array($actifs)) {
229 $page->assign('retour', $redirect->modify_email($actifs,
230 Env::v('emails_rewrite',Array())));
231 }
232 }
233
234 $res = XDB::query(
235 "SELECT alias
236 FROM virtual
237 INNER JOIN virtual_redirect USING(vid)
238 WHERE (redirect={?} OR redirect={?})
239 AND alias LIKE '%@{$globals->mail->alias_dom}'",
240 $forlife.'@'.$globals->mail->domain, $forlife.'@'.$globals->mail->domain2);
241 $melix = $res->fetchOneCell();
242 if ($melix) {
243 list($melix) = explode('@', $melix);
244 $page->assign('melix',$melix);
245 }
246
247 $res = XDB::query(
248 "SELECT alias,expire
249 FROM aliases
250 WHERE id={?} AND (type='a_vie' OR type='alias')
251 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $uid);
252 $page->assign('alias', $res->fetchAllAssoc());
253 $page->assign('emails',$redirect->emails);
254 }
255
256 function handler_antispam(&$page, $statut_filtre = null)
257 {
258 require_once 'emails.inc.php';
259 require_once('wiki.inc.php');
260 wiki_require_page('Xorg.Antispam');
261
262 $page->changeTpl('emails/antispam.tpl');
263
264 $bogo = new Bogo(S::v('uid'));
265 if (isset($statut_filtre)) {
266 $bogo->change(S::v('uid'), $statut_filtre + 0);
267 }
268 $page->assign('filtre',$bogo->level());
269 }
270
271 function handler_submit(&$page)
272 {
273 require_once('wiki.inc.php');
274 wiki_require_page('Xorg.Mails');
275 $page->changeTpl('emails/submit_spam.tpl');
276
277 if (Post::has('send_email')) {
278 $upload = PlUpload::get($_FILES['mail'], S::v('forlife'), 'spam.submit', true);
279 if (!$upload) {
280 $page->trig('Une erreur a été rencontrée lors du transfert du fichier');
281 return;
282 }
283 $mime = $upload->contentType();
284 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
285 $upload->clear();
286 $page->trig('Le fichier ne contient pas un mail complet');
287 return;
288 }
289 global $globals;
290 $box = Post::v('type') . '@' . $globals->mail->domain;
291 $mailer = new PlMailer();
292 $mailer->addTo($box);
293 $mailer->setFrom('"' . S::v('prenom') . ' ' . S::v('nom') . '" <web@' . $globals->mail->domain . '>');
294 $mailer->setTxtBody(Post::v('type') . ' soumis par ' . S::v('forlife') . ' via le web');
295 $mailer->addUploadAttachment($upload, Post::v('type') . '.mail');
296 $mailer->send();
297 $page->trig('Le message a été transmis à ' . $box);
298 $upload->clear();
299 }
300 }
301
302 function handler_send(&$page)
303 {
304 global $globals;
305 $page->changeTpl('emails/send.tpl');
306 $page->addJsLink('ajax.js');
307
308 $page->assign('xorg_title','Polytechnique.org - Envoyer un email');
309
310 // action si on recoit un formulaire
311 if (Env::v('submit') == 'Envoyer')
312 {
313 function getEmails($aliases)
314 {
315 if (!is_array($aliases)) {
316 return null;
317 }
318 $rel = Env::v('contacts');
319 $ret = array();
320 foreach ($aliases as $alias) {
321 $ret[$alias] = $rel[$alias];
322 }
323 return join(', ', $ret);
324 }
325
326 foreach ($_FILES as &$file) {
327 if ($file['name'] && !PlUpload::get($file, S::v('forlife'), 'emails.send', false)) {
328 $page->trig("Impossible de télécharger '" . pl_entities($file['name']) . "'");
329 }
330 }
331
332 $to2 = getEmails(Env::v('to_contacts'));
333 $cc2 = getEmails(Env::v('cc_contacts'));
334 $txt = str_replace('^M', '', Env::v('contenu'));
335 $to = Env::v('to');
336 $subj = Env::v('sujet');
337 $from = Env::v('from');
338 $cc = trim(Env::v('cc'));
339 $bcc = trim(Env::v('bcc'));
340
341 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
342 $page->trig("Indique au moins un destinataire.");
343 $page->assign('uploaded_f', PlUpload::listFilenames(S::v('forlife'), 'emails.send'));
344 } else {
345 $mymail = new PlMailer();
346 $mymail->setFrom($from);
347 $mymail->setSubject($subj);
348 if (!empty($to)) { $mymail->addTo($to); }
349 if (!empty($cc)) { $mymail->addCc($cc); }
350 if (!empty($bcc)) { $mymail->addBcc($bcc); }
351 if (!empty($to2)) { $mymail->addTo($to2); }
352 if (!empty($cc2)) { $mymail->addCc($cc2); }
353 $files =& PlUpload::listFiles(S::v('forlife'), 'emails.send');
354 foreach ($files as $name=>&$upload) {
355 $mymail->addUploadAttachment($upload, $name);
356 }
357 if (Env::v('nowiki')) {
358 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
359 } else {
360 $mymail->setWikiBody($txt);
361 }
362 if ($mymail->send()) {
363 $page->trig("Ton mail a bien été envoyé.");
364 $_REQUEST = array('bcc' => S::v('bestalias').'@'.$globals->mail->domain);
365 PlUpload::clear(S::v('forlife'), 'emails.send');
366 } else {
367 $page->trig("Erreur lors de l'envoi du courriel, réessaye.");
368 $page->assign('uploaded_f', PlUpload::listFilenames(S::v('forlife'), 'emails.send'));
369 }
370 }
371 } else {
372 PlUpload::clear(S::v('forlife'), 'emails.send');
373 $_REQUEST['bcc'] = S::v('bestalias').'@'.$globals->mail->domain;
374 }
375
376 $res = XDB::query(
377 "SELECT u.prenom, u.nom, u.promo, a.alias as forlife
378 FROM auth_user_md5 AS u
379 INNER JOIN contacts AS c ON (u.user_id = c.contact)
380 INNER JOIN aliases AS a ON (u.user_id=a.id AND FIND_IN_SET('bestalias',a.flags))
381 WHERE c.uid = {?}
382 ORDER BY u.nom, u.prenom", S::v('uid'));
383 $page->assign('contacts', $res->fetchAllAssoc());
384 $page->assign('maxsize', ini_get('post_max_size') . 'o');
385 }
386
387 function handler_broken(&$page, $warn = null, $email = null)
388 {
389 require_once 'emails.inc.php';
390 require_once('wiki.inc.php');
391 wiki_require_page('Xorg.PatteCassée');
392
393 global $globals;
394
395 $page->changeTpl('emails/broken.tpl');
396
397 if ($warn == 'warn' && $email) {
398 $email = valide_email($email);
399 // vérifications d'usage
400 $sel = XDB::query(
401 "SELECT e.uid, a.alias
402 FROM emails AS e
403 INNER JOIN auth_user_md5 AS u ON e.uid = u.user_id
404 INNER JOIN aliases AS a ON (e.uid = a.id AND type!='homonyme'
405 AND FIND_IN_SET('bestalias',a.flags))
406 WHERE e.email={?}", $email);
407
408 if (list($uid, $dest) = $sel->fetchOneRow()) {
409 // envoi du mail
410 $message = "Bonjour !
411
412 Ce mail a été généré automatiquement par le service de patte cassée de
413 Polytechnique.org car un autre utilisateur, ".S::v('prenom').' '.S::v('nom').",
414 nous a signalé qu'en t'envoyant un mail, il avait reçu un message d'erreur
415 indiquant que ton adresse de redirection $email
416 ne fonctionnait plus !
417
418 Nous te suggérons de vérifier cette adresse, et le cas échéant de mettre
419 à jour sur le site <{$globals->baseurl}/emails> tes adresses
420 de redirection...
421
422 Pour plus de rensignements sur le service de patte cassée, n'hésites pas à
423 consulter la page <{$globals->baseurl}/emails/broken>.
424
425
426 A bientôt sur Polytechnique.org !
427 L'équipe d'administration <support@polytechnique.org>";
428
429 $mail = new PlMailer();
430 $mail->setFrom('"Polytechnique.org" <support@polytechnique.org>');
431 $mail->addTo("$dest@polytechnique.org");
432 $mail->setSubject("Une de tes adresse de redirection Polytechnique.org ne marche plus !!");
433 $mail->setTxtBody($message);
434 $mail->send();
435 $page->trig("Mail envoyé ! :o)");
436 }
437 } elseif (Post::has('email')) {
438 $email = valide_email(Post::v('email'));
439
440 list(,$fqdn) = explode('@', $email);
441 $fqdn = strtolower($fqdn);
442 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org'
443 || $fqdn == 'm4x.org' || $fqdn == 'melix.net')
444 {
445 $page->assign('neuneu', true);
446 } else {
447 $page->assign('email',$email);
448 $sel = XDB::query(
449 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
450 u.nom, u.prenom, u.promo, a.alias AS forlife
451 FROM emails as e1
452 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
453 AND FIND_IN_SET('active', e2.flags)
454 AND e1.email != e2.email)
455 INNER JOIN auth_user_md5 as u ON(e1.uid = u.user_id)
456 INNER JOIN aliases AS a ON (a.id = e1.uid AND a.type = 'a_vie')
457 WHERE e1.email = {?}
458 GROUP BY e1.uid", $email);
459 if ($x = $sel->fetchOneAssoc()) {
460 // on écrit dans la base que l'adresse est cassée
461 if (!$x['panne']) {
462 XDB::execute("UPDATE emails
463 SET panne=NOW(),
464 last=NOW(),
465 panne_level = 1
466 WHERE email = {?}", $email);
467 } else {
468 XDB::execute("UPDATE emails
469 SET panne_level = 1
470 WHERE email = {?} AND panne_level = 0", $email);
471 }
472 $page->assign_by_ref('x', $x);
473 }
474 }
475 }
476 }
477
478 function handler_duplicated(&$page, $action = 'list', $email = null)
479 {
480 $page->changeTpl('emails/duplicated.tpl');
481
482 $states = array('pending' => 'En attente...',
483 'safe' => 'Pas d\'inquiétude',
484 'unsafe' => 'Recherches en cours',
485 'dangerous' => 'Usurpations par cette adresse');
486 $page->assign('states', $states);
487
488 switch (Post::v('action')) {
489 case 'create':
490 if (trim(Post::v('emailN')) != '') {
491 Xdb::execute('INSERT IGNORE INTO emails_watch (email, state, detection, last, uid, description)
492 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
493 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
494 };
495 break;
496
497 case 'edit':
498 Xdb::execute('UPDATE emails_watch
499 SET state = {?}, last = NOW(), uid = {?}, description = {?}
500 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
501 break;
502
503 default:
504 if ($action == 'delete' && !is_null($email)) {
505 Xdb::execute('DELETE FROM emails_watch WHERE email = {?}', $email);
506 }
507 }
508 if ($action != 'create' && $action != 'edit') {
509 $action = 'list';
510 }
511 $page->assign('action', $action);
512
513 if ($action == 'list') {
514 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
515 FROM emails_watch AS w
516 LEFT JOIN emails AS e USING(email)
517 LEFT JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
518 ORDER BY w.state, w.email, a.alias";
519 $it = Xdb::iterRow($sql);
520
521 $table = array();
522 $props = array();
523 while (list($email, $date, $state, $forlife) = $it->next()) {
524 if (count($props) == 0 || $props['mail'] != $email) {
525 if (count($props) > 0) {
526 $table[] = $props;
527 }
528 $props = array('mail' => $email,
529 'detection' => $date,
530 'state' => $state,
531 'users' => array($forlife));
532 } else {
533 $props['users'][] = $forlife;
534 }
535 }
536 if (count($props) > 0) {
537 $table[] = $props;
538 }
539 $page->assign('table', $table);
540 } elseif ($action == 'edit') {
541 $sql = "SELECT w.detection, w.state, w.last, w.description,
542 a1.alias AS edit, a2.alias AS forlife
543 FROM emails_watch AS w
544 LEFT JOIN aliases AS a1 ON (a1.id = w.uid AND a1.type = 'a_vie')
545 LEFT JOIN emails AS e ON (w.email = e.email)
546 LEFT JOIN aliases AS a2 ON (a2.id = e.uid AND a2.type = 'a_vie')
547 WHERE w.email = {?}
548 ORDER BY a2.alias";
549 $it = Xdb::iterRow($sql, $email);
550
551 $props = array();
552 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
553 if (count($props) == 0) {
554 $props = array('mail' => $email,
555 'detection' => $detection,
556 'state' => $state,
557 'last' => $last,
558 'description' => $description,
559 'edit' => $edit,
560 'users' => array($forlife));
561 } else {
562 $props['users'][] = $forlife;
563 }
564 }
565 $page->assign('doublon', $props);
566 }
567 }
568 function handler_lost(&$page, $action = 'list', $email = null)
569 {
570 $page->changeTpl('emails/lost.tpl');
571
572 $page->assign('lost_emails', XDB::iterator('
573 SELECT u.user_id, a.alias
574 FROM auth_user_md5 AS u
575 INNER JOIN aliases AS a ON (a.id = u.user_id AND a.type = "a_vie")
576 LEFT JOIN emails AS e ON (u.user_id=e.uid AND FIND_IN_SET("active",e.flags))
577 WHERE e.uid IS NULL AND u.deces = 0
578 ORDER BY u.promo DESC, u.nom, u.prenom'));
579 }
580 }
581
582 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
583 ?>