Bugfixes and improvements
[platal.git] / modules / axletter.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 AXLetterModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'ax' => $this->make_hook('index', AUTH_COOKIE),
28 'ax/out' => $this->make_hook('out', AUTH_PUBLIC),
29 'ax/show' => $this->make_hook('show', AUTH_COOKIE),
30 'ax/edit' => $this->make_hook('submit', AUTH_MDP),
31 'ax/edit/cancel' => $this->make_hook('cancel', AUTH_MDP),
32 'ax/edit/valid' => $this->make_hook('valid', AUTH_MDP),
33 'admin/axletter' => $this->make_hook('admin', AUTH_MDP, 'admin'),
34 );
35 }
36
37 function handler_out(&$page, $hash = null)
38 {
39 if (!$hash) {
40 if (!S::logged()) {
41 return PL_DO_AUTH;
42 } else {
43 return $this->handler_index($page, 'out');
44 }
45 }
46 $this->load('axletter.inc.php');
47 $page->changeTpl('axletter/unsubscribe.tpl');
48 $page->assign('success', AXLetter::unsubscribe($hash, true));
49 }
50
51 function handler_index(&$page, $action = null)
52 {
53 $this->load('axletter.inc.php');
54
55 $page->changeTpl('axletter/index.tpl');
56 $page->setTitle('Envois de l\'AX');
57
58 switch ($action) {
59 case 'in': AXLetter::subscribe(); break;
60 case 'out': AXLetter::unsubscribe(); break;
61 }
62
63 $perm = AXLetter::hasPerms();
64 if ($perm) {
65 $res = XDB::query("SELECT * FROM axletter_ins");
66 $page->assign('count', $res->numRows());
67 $page->assign('new', AXLetter::awaiting());
68 }
69 $page->assign('axs', AXLetter::subscriptionState());
70 $page->assign('ax_list', AXLetter::listSent());
71 $page->assign('ax_rights', $perm);
72 }
73
74 function handler_submit(&$page, $action = null)
75 {
76 $this->load('axletter.inc.php');
77 if (!AXLetter::hasPerms()) {
78 return PL_FORBIDDEN;
79 }
80
81 $page->changeTpl('axletter/edit.tpl');
82
83 $saved = Post::i('saved');
84 $new = false;
85 $id = Post::i('id');
86 $short_name = trim(Post::v('short_name'));
87 $subject = trim(Post::v('subject'));
88 $title = trim(Post::v('title'));
89 $body = rtrim(Post::v('body'));
90 $signature = trim(Post::v('signature'));
91 $promo_min = Post::i('promo_min');
92 $promo_max = Post::i('promo_max');
93 $subset_to = preg_split("/[ ,;\:\n\r]+/", Post::v('subset_to'), -1, PREG_SPLIT_NO_EMPTY);
94 $subset = ( count($subset_to) > 0);
95 $echeance = Post::has('echeance_date') ?
96 preg_replace('/^(\d\d\d\d)(\d\d)(\d\d)$/', '\1-\2-\3', Post::v('echeance_date')) . ' ' . Post::v('echeance_time')
97 : Post::v('echeance');
98 $echeance_date = Post::v('echeance_date');
99 $echeance_time = Post::v('echeance_time');
100
101 if (!$id) {
102 $res = XDB::query("SELECT * FROM axletter WHERE FIND_IN_SET('new', bits)");
103 if ($res->numRows()) {
104 extract($res->fetchOneAssoc(), EXTR_OVERWRITE);
105 if ($subset) {
106 $res = XDB::query('SELECT email FROM axletter_subsets WHERE letter_id = {?}', $id);
107 $subset_to = $res->fetchColumn();
108 }
109 $saved = true;
110 } else {
111 XDB::execute("INSERT INTO axletter SET id = NULL");
112 $id = XDB::insertId();
113 }
114 if (!$echeance || $echeance == '0000-00-00 00:00:00') {
115 $saved = false;
116 $new = true;
117 }
118 } elseif (Post::has('valid')) {
119 S::assert_xsrf_token();
120
121 if (!$subject && $title) {
122 $subject = $title;
123 }
124 if (!$title && $subject) {
125 $title = $subject;
126 }
127 if (!$subject || !$title || !$body) {
128 $page->trigError("L'article doit avoir un sujet et un contenu");
129 Post::kill('valid');
130 }
131 if (($promo_min > $promo_max && $promo_max != 0)||
132 ($promo_min != 0 && ($promo_min <= 1900 || $promo_min >= 2020)) ||
133 ($promo_max != 0 && ($promo_max <= 1900 || $promo_max >= 2020)))
134 {
135 $page->trigError("L'intervalle de promotions n'est pas valide");
136 Post::kill('valid');
137 }
138 if (empty($short_name)) {
139 $page->trigError("L'annonce doit avoir un nom raccourci pour simplifier la navigation dans les archives");
140 Post::kill('valid');
141 } elseif (!preg_match('/^[a-z][-a-z0-9]*[a-z0-9]$/', $short_name)) {
142 $page->trigError("Le nom raccourci n'est pas valide, il doit comporter au moins 2 caractères et n'être composé "
143 . "que de chiffres, lettres et tirets");
144 Post::kill('valid');
145 } elseif ($short_name != Post::v('old_short_name')) {
146 $res = XDB::query("SELECT id FROM axletter WHERE short_name = {?}", $short_name);
147 if ($res->numRows() && $res->fetchOneCell() != $id) {
148 $page->trigError("Le nom $short_name est déjà utilisé, merci d'en choisir un autre");
149 $short_name = Post::v('old_short_name');
150 if (empty($short_name)) {
151 Post::kill('valid');
152 }
153 }
154 }
155
156 switch (@Post::v('valid')) {
157 case 'Aperçu':
158 $this->load('axletter.inc.php');
159 $al = new AXLetter(array($id, $short_name, $subject, $title, $body, $signature,
160 $promo_min, $promo_max, $subset, $echeance, 0, 'new'));
161 $al->toHtml($page, S::v('prenom'), S::v('nom'), S::v('femme'));
162 break;
163
164 case 'Confirmer':
165 XDB::execute("REPLACE INTO axletter
166 SET id = {?}, short_name = {?}, subject = {?}, title = {?}, body = {?},
167 signature = {?}, promo_min = {?}, promo_max = {?}, echeance = {?}, subset = {?}",
168 $id, $short_name, $subject, $title, $body, $signature, $promo_min, $promo_max, $echeance, $subset);
169 if ($subset) {
170 XDB::execute('DELETE FROM axletter_subsets
171 WHERE letter_id = {?}', $id);
172 foreach ($subset_to as $email) {
173 $uid = $this->idFromMail(array('email' => $email));
174 if ($uid) {
175 XDB::execute('INSERT INTO axletter_subsets
176 SET letter_id = {?}, user_id = {?}, email = {?}',
177 $id, $uid, $email);
178 }
179 }
180 }
181 if (!$saved) {
182 global $globals;
183 $mailer = new PlMailer();
184 $mailer->setFrom("support@" . $globals->mail->domain);
185 $mailer->setSubject("Un nouveau projet d'email de l'AX vient d'être proposé");
186 $mailer->setTxtBody("Un nouvel email vient d'être rédigé en prévision d'un envoi prochain. Vous pouvez "
187 . "le modifier jusqu'à ce qu'il soit verrouillé pour l'envoi\n\n"
188 . "Le sujet de l'email : $subject\n"
189 . "L'échéance d'envoi est fixée à $echeance.\n"
190 . "L'email pourra néanmoins partir avant cette échéance si un administrateur de "
191 . "Polytechnique.org le valide.\n\n"
192 . "Pour modifier, valider ou annuler l'email :\n"
193 . "https://www.polytechnique.org/ax/edit\n"
194 . "-- \n"
195 . "Association Polytechnique.org\n");
196 $res = XDB::iterRow("SELECT IF(u.nom_usage != '', u.nom_usage, u.nom) AS nom,
197 u.prenom, a.alias AS bestalias
198 FROM axletter_rights AS ar
199 INNER JOIN auth_user_md5 AS u USING(user_id)
200 INNER JOIN aliases AS a ON (u.user_id = a.id
201 AND FIND_IN_SET('bestalias', a.flags))");
202 while (list($nom, $prenom, $alias) = $res->next()) {
203 $mailer->addTo("$nom $prenom <$alias@{$globals->mail->domain}>");
204 }
205 $mailer->send();
206 }
207 $saved = true;
208 $echeance_date = null;
209 $echeance_time = null;
210 pl_redirect('ax');
211 break;
212 }
213 }
214 $page->assign('id', $id);
215 $page->assign('short_name', $short_name);
216 $page->assign('subject', $subject);
217 $page->assign('title', $title);
218 $page->assign('body', $body);
219 $page->assign('signature', $signature);
220 $page->assign('promo_min', $promo_min);
221 $page->assign('promo_max', $promo_max);
222 $page->assign('subset_to', implode("\n", $subset_to));
223 $page->assign('subset', $subset);
224 $page->assign('echeance', $echeance);
225 $page->assign('echeance_date', $echeance_date);
226 $page->assign('echeance_time', $echeance_time);
227 $page->assign('saved', $saved);
228 $page->assign('new', $new);
229 $page->assign('is_xorg', S::admin());
230
231 if (!$saved) {
232 $select = '';
233 for ($i = 0 ; $i < 24 ; $i++) {
234 $stamp = sprintf('%02d:00:00', $i);
235 if ($stamp == $echeance_time) {
236 $sel = ' selected="selected"';
237 } else {
238 $sel = '';
239 }
240 $select .= "<option value=\"$stamp\"$sel>{$i}h</option>\n";
241 }
242 $page->assign('echeance_time', $select);
243 }
244 }
245
246 function handler_cancel(&$page, $force = null)
247 {
248 $this->load('axletter.inc.php');
249 if (!AXLetter::hasPerms() || !S::has_xsrf_token()) {
250 return PL_FORBIDDEN;
251 }
252
253 $al = AXLetter::awaiting();
254 if (!$al) {
255 $page->kill("Aucune lettre en attente");
256 return;
257 }
258 if (!$al->invalid()) {
259 $page->kill("Une erreur est survenue lors de l'annulation de l'envoi");
260 return;
261 }
262
263 $page->killSuccess("L'envoi de l'annonce {$al->title()} est annulé.");
264 }
265
266 function handler_valid(&$page, $force = null)
267 {
268 $this->load('axletter.inc.php');
269 if (!AXLetter::hasPerms() || !S::has_xsrf_token()) {
270 return PL_FORBIDDEN;
271 }
272
273 $al = AXLetter::awaiting();
274 if (!$al) {
275 $page->kill("Aucune lettre en attente");
276 return;
277 }
278 if (!$al->valid()) {
279 $page->kill("Une erreur est survenue lors de la validation de l'envoi");
280 return;
281 }
282
283 $page->killSuccess("L'envoi de l'annonce aura lieu dans l'heure qui vient.");
284 }
285
286 function handler_show(&$page, $nid = 'last')
287 {
288 $this->load('axletter.inc.php');
289 $page->changeTpl('axletter/show.tpl');
290
291 try {
292 $nl = new AXLetter($nid);
293 if (Get::has('text')) {
294 $nl->toText($page, S::v('prenom'), S::v('nom'), S::v('femme'));
295 } else {
296 $nl->toHtml($page, S::v('prenom'), S::v('nom'), S::v('femme'));
297 }
298 if (Post::has('send')) {
299 $nl->sendTo(S::user()->login(), S::user()->bestEmail(),
300 S::v('prenom'), S::v('nom'),
301 S::v('femme'), S::v('mail_fmt') != 'texte');
302 }
303 } catch (MailNotFound $e) {
304 return PL_NOT_FOUND;
305 }
306 }
307
308 function handler_admin(&$page, $action = null, $uid = null)
309 {
310 $this->load('axletter.inc.php');
311 if (Post::has('action')) {
312 $action = Post::v('action');
313 $uid = Post::v('uid');
314 }
315 if ($uid) {
316 S::assert_xsrf_token();
317
318 $uids = preg_split('/ *[,;\: ] */', $uid);
319 foreach ($uids as $uid) {
320 switch ($action) {
321 case 'add':
322 $res = AXLetter::grantPerms($uid);
323 break;
324 case 'del';
325 $res = AXLetter::revokePerms($uid);
326 break;
327 }
328 if (!$res) {
329 $page->trigError("Personne ne correspond à l'identifiant '$uid'");
330 }
331 }
332 }
333
334 $page->changeTpl('axletter/admin.tpl');
335 $res = XDB::iterator("SELECT IF(u.nom_usage != '', u.nom_usage, u.nom) AS nom,
336 u.prenom, u.promo, u.hruid
337 FROM axletter_rights AS ar
338 INNER JOIN auth_user_md5 AS u USING(user_id)");
339 $page->assign('admins', $res);
340
341 $importer = new CSVImporter('axletter_ins');
342 $importer->registerFunction('user_id', 'email vers Id X.org', array($this, 'idFromMail'));
343 $importer->forceValue('hash', array($this, 'createHash'));
344 $importer->apply($page, "admin/axletter", array('user_id', 'email', 'prenom', 'nom', 'promo', 'flag', 'hash'));
345 }
346
347 function idFromMail($line, $key, $relation = null)
348 {
349 static $field;
350 global $globals;
351 if (!isset($field)) {
352 $field = array('email', 'mail', 'login', 'bestalias', 'forlife', 'flag');
353 foreach ($field as $fld) {
354 if (isset($line[$fld])) {
355 $field = $fld;
356 break;
357 }
358 }
359 }
360 $email = $line[$field];
361 if (strpos($email, '@') === false) {
362 $user = $email;
363 $domain = $globals->mail->domain2;
364 } else {
365 list($user, $domain) = explode('@', $email);
366 }
367 if ($domain != $globals->mail->domain && $domain != $globals->mail->domain2
368 && $domain != $globals->mail->alias_dom && $domain != $globals->mail->alias_dom2) {
369 $res = XDB::query("SELECT uid FROM emails WHERE email = {?}", $email);
370 if ($res->numRows() == 1) {
371 return $res->fetchOneCell();
372 }
373 return '0';
374 }
375 list($user) = explode('+', $user);
376 list($user) = explode('_', $user);
377 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
378 $res = XDB::query("SELECT a.id
379 FROM virtual AS v
380 INNER JOIN virtual_redirect AS r USING(vid)
381 INNER JOIN aliases AS a ON (a.type = 'a_vie'
382 AND r.redirect = CONCAT(a.alias, '@{$globals->mail->domain2}'))
383 WHERE v.alias = CONCAT({?}, '@{$globals->mail->alias_dom}')", $user);
384 $id = $res->fetchOneCell();
385 return $id ? $id : '0';
386 }
387 $res = XDB::query("SELECT id FROM aliases WHERE alias = {?}", $user);
388 $id = $res->fetchOneCell();
389 return $id ? $id : '0';
390 }
391
392 function createHash($line, $key, $relation)
393 {
394 $hash = implode(time(), $line) . rand();
395 $hash = md5($hash);
396 return $hash;
397 }
398 }
399
400 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
401 ?>