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