Enables axletter mailings to a subset of subscribers
[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 = Post::b('subset_to');
94 $subset_to = preg_split("/ *[ ,;\:\n\r]+ */", Post::v('subset_to'));
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_subset 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 ($subset && !count($subset_to)) {
139 $page->trigError("La liste d'adresses mails sélectionnée est vide");
140 Post::kill('valid');
141 }
142 if (empty($short_name)) {
143 $page->trigError("L'annonce doit avoir un nom raccourci pour simplifier la navigation dans les archives");
144 Post::kill('valid');
145 } elseif (!preg_match('/^[a-z][-a-z0-9]*[a-z0-9]$/', $short_name)) {
146 $page->trigError("Le nom raccourci n'est pas valide, il doit comporter au moins 2 caractères et n'être composé "
147 . "que de chiffres, lettres et tirets");
148 Post::kill('valid');
149 } elseif ($short_name != Post::v('old_short_name')) {
150 $res = XDB::query("SELECT id FROM axletter WHERE short_name = {?}", $short_name);
151 if ($res->numRows() && $res->fetchOneCell() != $id) {
152 $page->trigError("Le nom $short_name est déjà utilisé, merci d'en choisir un autre");
153 $short_name = Post::v('old_short_name');
154 if (empty($short_name)) {
155 Post::kill('valid');
156 }
157 }
158 }
159
160 switch (@Post::v('valid')) {
161 case 'Aperçu':
162 $this->load('axletter.inc.php');
163 $al = new AXLetter(array($id, $short_name, $subject, $title, $body, $signature,
164 $promo_min, $promo_max, $subset, $echeance, 0, 'new'));
165 $al->toHtml($page, S::v('prenom'), S::v('nom'), S::v('femme'));
166 break;
167
168 case 'Confirmer':
169 XDB::execute("REPLACE INTO axletter
170 SET id = {?}, short_name = {?}, subject = {?}, title = {?}, body = {?},
171 signature = {?}, promo_min = {?}, promo_max = {?}, echeance = {?}, subset = {?}",
172 $id, $short_name, $subject, $title, $body, $signature, $promo_min, $promo_max, $echeance, $subset);
173 if ($subset) {
174 XDB::execute('DELETE FROM axletter_subset WHERE letter_id = {?}', $id);
175 foreach ($subset_to as $email) {
176 // $email = trim($email);
177 $uid = $this->idFromMail(array('email' => $email));
178 if ($uid) {
179 XDB::execute('INSERT INTO axletter_subset SET letter_id = {?}, user_id = {?}, email = {?}', $id, $uid, $email);
180 }
181 }
182 }
183 if (!$saved) {
184 global $globals;
185 $mailer = new PlMailer();
186 $mailer->setFrom("support@" . $globals->mail->domain);
187 $mailer->setSubject("Un nouveau projet d'email de l'AX vient d'être proposé");
188 $mailer->setTxtBody("Un nouvel email vient d'être rédigé en prévision d'un envoi prochain. Vous pouvez "
189 . "le modifier jusqu'à ce qu'il soit verrouillé pour l'envoi\n\n"
190 . "Le sujet de l'email : $subject\n"
191 . "L'échéance d'envoi est fixée à $echeance.\n"
192 . "L'email pourra néanmoins partir avant cette échéance si un administrateur de "
193 . "Polytechnique.org le valide.\n\n"
194 . "Pour modifier, valider ou annuler l'email :\n"
195 . "https://www.polytechnique.org/ax/edit\n"
196 . "-- \n"
197 . "Association Polytechnique.org\n");
198 $res = XDB::iterRow("SELECT IF(u.nom_usage != '', u.nom_usage, u.nom) AS nom,
199 u.prenom, a.alias AS bestalias
200 FROM axletter_rights AS ar
201 INNER JOIN auth_user_md5 AS u USING(user_id)
202 INNER JOIN aliases AS a ON (u.user_id = a.id
203 AND FIND_IN_SET('bestalias', a.flags))");
204 while (list($nom, $prenom, $alias) = $res->next()) {
205 $mailer->addTo("$nom $prenom <$alias@{$globals->mail->domain}>");
206 }
207 $mailer->send();
208 }
209 $saved = true;
210 $echeance_date = null;
211 $echeance_time = null;
212 pl_redirect('ax');
213 break;
214 }
215 }
216 $page->assign('id', $id);
217 $page->assign('short_name', $short_name);
218 $page->assign('subject', $subject);
219 $page->assign('title', $title);
220 $page->assign('body', $body);
221 $page->assign('signature', $signature);
222 $page->assign('promo_min', $promo_min);
223 $page->assign('promo_max', $promo_max);
224 $page->assign('subset_to', implode("\n", $subset_to));
225 $page->assign('subset', $subset);
226 $page->assign('echeance', $echeance);
227 $page->assign('echeance_date', $echeance_date);
228 $page->assign('echeance_time', $echeance_time);
229 $page->assign('saved', $saved);
230 $page->assign('new', $new);
231 $page->assign('is_xorg', S::admin());
232
233 if (!$saved) {
234 $select = '';
235 for ($i = 0 ; $i < 24 ; $i++) {
236 $stamp = sprintf('%02d:00:00', $i);
237 if ($stamp == $echeance_time) {
238 $sel = ' selected="selected"';
239 } else {
240 $sel = '';
241 }
242 $select .= "<option value=\"$stamp\"$sel>{$i}h</option>\n";
243 }
244 $page->assign('echeance_time', $select);
245 }
246 }
247
248 function handler_cancel(&$page, $force = null)
249 {
250 $this->load('axletter.inc.php');
251 if (!AXLetter::hasPerms() || !S::has_xsrf_token()) {
252 return PL_FORBIDDEN;
253 }
254
255 $al = AXLetter::awaiting();
256 if (!$al) {
257 $page->kill("Aucune lettre en attente");
258 return;
259 }
260 if (!$al->invalid()) {
261 $page->kill("Une erreur est survenue lors de l'annulation de l'envoi");
262 return;
263 }
264
265 $page->killSuccess("L'envoi de l'annonce {$al->title()} est annulé.");
266 }
267
268 function handler_valid(&$page, $force = null)
269 {
270 $this->load('axletter.inc.php');
271 if (!AXLetter::hasPerms() || !S::has_xsrf_token()) {
272 return PL_FORBIDDEN;
273 }
274
275 $al = AXLetter::awaiting();
276 if (!$al) {
277 $page->kill("Aucune lettre en attente");
278 return;
279 }
280 if (!$al->valid()) {
281 $page->kill("Une erreur est survenue lors de la validation de l'envoi");
282 return;
283 }
284
285 $page->killSuccess("L'envoi de l'annonce aura lieu dans l'heure qui vient.");
286 }
287
288 function handler_show(&$page, $nid = 'last')
289 {
290 $this->load('axletter.inc.php');
291 $page->changeTpl('axletter/show.tpl');
292
293 try {
294 $nl = new AXLetter($nid);
295 if (Get::has('text')) {
296 $nl->toText($page, S::v('prenom'), S::v('nom'), S::v('femme'));
297 } else {
298 $nl->toHtml($page, S::v('prenom'), S::v('nom'), S::v('femme'));
299 }
300 if (Post::has('send')) {
301 $nl->sendTo(S::user()->login(), S::user()->bestEmail(),
302 S::v('prenom'), S::v('nom'),
303 S::v('femme'), S::v('mail_fmt') != 'texte');
304 }
305 } catch (MailNotFound $e) {
306 return PL_NOT_FOUND;
307 }
308 }
309
310 function handler_admin(&$page, $action = null, $uid = null)
311 {
312 $this->load('axletter.inc.php');
313 if (Post::has('action')) {
314 $action = Post::v('action');
315 $uid = Post::v('uid');
316 }
317 if ($uid) {
318 S::assert_xsrf_token();
319
320 $uids = preg_split('/ *[,;\: ] */', $uid);
321 foreach ($uids as $uid) {
322 switch ($action) {
323 case 'add':
324 $res = AXLetter::grantPerms($uid);
325 break;
326 case 'del';
327 $res = AXLetter::revokePerms($uid);
328 break;
329 }
330 if (!$res) {
331 $page->trigError("Personne ne correspond à l'identifiant '$uid'");
332 }
333 }
334 }
335
336 $page->changeTpl('axletter/admin.tpl');
337 $res = XDB::iterator("SELECT IF(u.nom_usage != '', u.nom_usage, u.nom) AS nom,
338 u.prenom, u.promo, u.hruid
339 FROM axletter_rights AS ar
340 INNER JOIN auth_user_md5 AS u USING(user_id)");
341 $page->assign('admins', $res);
342
343 $importer = new CSVImporter('axletter_ins');
344 $importer->registerFunction('user_id', 'email vers Id X.org', array($this, 'idFromMail'));
345 $importer->forceValue('hash', array($this, 'createHash'));
346 $importer->apply($page, "admin/axletter", array('user_id', 'email', 'prenom', 'nom', 'promo', 'flag', 'hash'));
347 }
348
349 function idFromMail($line, $key, $relation = null)
350 {
351 static $field;
352 global $globals;
353 if (!isset($field)) {
354 $field = array('email', 'mail', 'login', 'bestalias', 'forlife', 'flag');
355 foreach ($field as $fld) {
356 if (isset($line[$fld])) {
357 $field = $fld;
358 break;
359 }
360 }
361 }
362 $email = $line[$field];
363 if (strpos($email, '@') === false) {
364 $user = $email;
365 $domain = $globals->mail->domain2;
366 } else {
367 list($user, $domain) = explode('@', $email);
368 }
369 if ($domain != $globals->mail->domain && $domain != $globals->mail->domain2
370 && $domain != $globals->mail->alias_dom && $domain != $globals->mail->alias_dom2) {
371 $res = XDB::query("SELECT uid FROM emails WHERE email = {?}", $email);
372 if ($res->numRows() == 1) {
373 return $res->fetchOneCell();
374 }
375 return '0';
376 }
377 list($user) = explode('+', $user);
378 list($user) = explode('_', $user);
379 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
380 $res = XDB::query("SELECT a.id
381 FROM virtual AS v
382 INNER JOIN virtual_redirect AS r USING(vid)
383 INNER JOIN aliases AS a ON (a.type = 'a_vie'
384 AND r.redirect = CONCAT(a.alias, '@{$globals->mail->domain2}'))
385 WHERE v.alias = CONCAT({?}, '@{$globals->mail->alias_dom}')", $user);
386 $id = $res->fetchOneCell();
387 return $id ? $id : '0';
388 }
389 $res = XDB::query("SELECT id FROM aliases WHERE alias = {?}", $user);
390 $id = $res->fetchOneCell();
391 return $id ? $id : '0';
392 }
393
394 function createHash($line, $key, $relation)
395 {
396 $hash = implode(time(), $line) . rand();
397 $hash = md5($hash);
398 return $hash;
399 }
400 }
401
402 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
403 ?>