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