Moving to GitHub.
[platal.git] / modules / newsletter.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2014 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 NewsletterModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'nl' => $this->make_hook('nl', AUTH_COOKIE, 'user'),
28 'nl/show' => $this->make_hook('nl_show', AUTH_COOKIE, 'user'),
29 'nl/search' => $this->make_hook('nl_search', AUTH_COOKIE, 'user'),
30 'nl/submit' => $this->make_hook('nl_submit', AUTH_PASSWD, 'user'),
31 'nl/remaining' => $this->make_hook('nl_remaining', AUTH_PASSWD, 'user'),
32 'admin/nls' => $this->make_hook('admin_nl_groups', AUTH_PASSWD, 'admin'),
33 'admin/newsletter' => $this->make_hook('admin_nl', AUTH_PASSWD, 'admin'),
34 'admin/newsletter/categories' => $this->make_hook('admin_nl_cat', AUTH_PASSWD, 'admin'),
35 'admin/newsletter/edit' => $this->make_hook('admin_nl_edit', AUTH_PASSWD, 'admin'),
36 'admin/newsletter/edit/delete' => $this->make_hook('admin_nl_delete', AUTH_PASSWD, 'admin'),
37 'stat/newsletter' => $this->make_hook('stat_nl', AUTH_PASSWD, 'admin')
38 // Automatic mailing is disabled for X.org NL
39 // 'admin/newsletter/edit/cancel' => $this->make_hook('cancel', AUTH_PASSWD, 'admin'),
40 // 'admin/newsletter/edit/valid' => $this->make_hook('valid', AUTH_PASSWD, 'admin'),
41 );
42 }
43
44 /** This function should return the adequate NewsLetter object for the current module.
45 */
46 protected function getNl()
47 {
48 require_once 'newsletter.inc.php';
49 return NewsLetter::forGroup(NewsLetter::GROUP_XORG);
50 }
51
52 function handler_nl($page, $action = null, $hash = null, $issue_id = null)
53 {
54 $nl = $this->getNl();
55 if (!$nl) {
56 return PL_NOT_FOUND;
57 }
58
59 $hash = ($hash == 'nohash') ? null : $hash;
60 switch ($action) {
61 case 'out':
62 $success = $nl->unsubscribe($issue_id, $hash, $hash != null);
63 if (!is_null($hash)) {
64 if ($success) {
65 $page->trigSuccess('La désinscription a été effectuée avec succès.');
66 } else {
67 $page->trigError("La désinscription n'a été pas pu être effectuée.");
68 }
69 return;
70 }
71 break;
72 case 'in': $nl->subscribe(); break;
73 default: ;
74 }
75
76 $page->changeTpl('newsletter/index.tpl');
77 $page->setTitle('Lettres mensuelles');
78
79 $page->assign_by_ref('nl', $nl);
80 $page->assign('nls', $nl->subscriptionState());
81 $page->assign('nl_list', $nl->listSentIssues(true));
82 }
83
84 function handler_nl_show($page, $nid = 'last')
85 {
86 $page->changeTpl('newsletter/show.tpl');
87 $nl = $this->getNl();
88 if (!$nl) {
89 return PL_NOT_FOUND;
90 }
91
92 try {
93 $issue = $nl->getIssue($nid);
94 $user =& S::user();
95 if (Get::has('text')) {
96 $issue->toText($page, $user);
97 } else {
98 $issue->toHtml($page, $user);
99 }
100 if (Post::has('send')) {
101 $issue->sendTo($user);
102 }
103 } catch (MailNotFound $e) {
104 return PL_NOT_FOUND;
105 }
106 }
107
108 function handler_nl_search($page)
109 {
110 S::assert_xsrf_token();
111 $nl = $this->getNl();
112 if (!$nl) {
113 return PL_NOT_FOUND;
114 }
115
116 if (!Post::has('nl_search')) {
117 pl_redirect($nl->prefix(true, false));
118 }
119
120 $nl_search = Post::t('nl_search');
121 $nl_search_type = Post::t('nl_search_type');
122 if (!$nl_search || !($nl_search_type > 0 && $nl_search_type < 10)) {
123 $page->trigErrorRedirect('La recherche est vide ou erronée.', $nl->prefix());
124 }
125
126 $page->changeTpl('newsletter/search.tpl');
127 $user = S::user();
128 $fields = array(1 => 'all', 2 => 'all', 3 => 'title', 4 => 'body', 5 => 'append', 6 => 'all', 7 => 'title', 8 => 'head', 9 => 'signature');
129 $res_articles = $res_issues = array();
130 if ($nl_search_type < 6) {
131 $res_articles = $nl->articleSearch($nl_search, $fields[$nl_search_type], $user);
132 }
133 if ($nl_search_type > 5 || $nl_search_type == 1) {
134 $res_issues = $nl->issueSearch($nl_search, $fields[$nl_search_type], $user);
135 }
136
137 $articles_count = count($res_articles);
138 $issues_count = count($res_issues);
139 $results_count = $articles_count + $issues_count;
140 if ($results_count > 200) {
141 $page->trigError('Recherche trop générale.');
142 } elseif ($results_count == 0) {
143 $page->trigWarning('Aucun résultat pour cette recherche.');
144 } else {
145 $page->assign('res_articles', $res_articles);
146 $page->assign('res_issues', $res_issues);
147 $page->assign('articles_count', $articles_count);
148 $page->assign('issues_count', $issues_count);
149 }
150
151 $page->assign_by_ref('nl', $nl);
152 $page->assign('nl_search', $nl_search);
153 $page->assign('nl_search_type', $nl_search_type);
154 $page->assign('results_count', $results_count);
155 }
156
157 function handler_nl_submit($page)
158 {
159 $page->changeTpl('newsletter/submit.tpl');
160
161 $nl = $this->getNl();
162 if (!$nl) {
163 return PL_NOT_FOUND;
164 }
165
166 $wp = new PlWikiPage('Xorg.LettreMensuelle');
167 $wp->buildCache();
168
169 if (Post::has('see') || (Post::has('valid') && (!trim(Post::v('title')) || !trim(Post::v('body'))))) {
170 if (!Post::has('see')) {
171 $page->trigError("L'article doit avoir un titre et un contenu");
172 }
173 $art = new NLArticle(Post::v('title'), Post::v('body'), Post::v('append'));
174 $page->assign('art', $art);
175 } elseif (Post::has('valid')) {
176 $art = new NLReq(S::user(), Post::v('title'),
177 Post::v('body'), Post::v('append'));
178 $art->submit();
179 $page->assign('submited', true);
180 }
181 $page->addCssLink($nl->cssFile());
182 }
183
184 function handler_nl_remaining($page)
185 {
186 require_once 'newsletter.inc.php';
187
188 pl_content_headers('text/html');
189 $page->changeTpl('newsletter/remaining.tpl', NO_SKIN);
190
191 $article = new NLArticle('', Post::t('body'), '');
192 $rest = $article->remain();
193
194 $page->assign('too_long', $rest['remaining_lines'] < 0);
195 $page->assign('last_line', ($rest['remaining_lines'] == 0));
196 $page->assign('remaining', ($rest['remaining_lines'] == 0) ? $rest['remaining_characters_for_last_line'] : $rest['remaining_lines']);
197 }
198
199 function handler_admin_nl($page, $new = false) {
200 $page->changeTpl('newsletter/admin.tpl');
201 $page->setTitle('Administration - Newsletter : liste');
202
203 $nl = $this->getNl();
204 if (!$nl) {
205 return PL_NOT_FOUND;
206 }
207
208 if ($new == 'new') {
209 // Logs NL creation.
210 S::logger()->log('nl_issue_create', $nid);
211
212 $id = $nl->createPending();
213 pl_redirect($nl->adminPrefix(true, false) . '/edit/' . $id);
214 }
215
216 $page->assign_by_ref('nl', $nl);
217 $page->assign('nl_list', $nl->listAllIssues());
218 }
219
220 function handler_admin_nl_groups($page, $sort = 'id', $order = 'ASC')
221 {
222 require_once 'newsletter.inc.php';
223
224 static $titles = array(
225 'id' => 'Id',
226 'group_name' => 'Groupe',
227 'name' => 'Titre',
228 'criteria' => 'Critères actifs'
229 );
230 static $next_orders = array(
231 'ASC' => 'DESC',
232 'DESC' => 'ASC'
233 );
234
235 if (!array_key_exists($sort, $titles)) {
236 $sort = 'id';
237 }
238 if (!in_array($order, array('ASC', 'DESC'))) {
239 $order = 'ASC';
240 }
241
242 $page->changeTpl('newsletter/admin_all.tpl');
243 $page->setTitle('Administration - Newsletters : Liste des Newsletters');
244 $page->assign('nls', Newsletter::getAll($sort, $order));
245 $page->assign('sort', $sort);
246 $page->assign('order', $order);
247 $page->assign('next_order', $next_orders[$order]);
248 $page->assign('titles', $titles);
249 }
250
251 function handler_admin_nl_edit($page, $nid = 'last', $aid = null, $action = 'edit') {
252 $page->changeTpl('newsletter/edit.tpl');
253 $page->addCssLink('nl.Polytechnique.org.css');
254 $page->setTitle('Administration - Newsletter : Édition');
255
256 $nl = $this->getNl();
257 if (!$nl) {
258 return PL_NOT_FOUND;
259 }
260
261 try {
262 $issue = $nl->getIssue($nid, false);
263 } catch (MailNotFound $e) {
264 return PL_NOT_FOUND;
265 }
266
267 $ufb = $nl->getSubscribersUFB();
268 $ufb_keepenv = false; // Will be set to True if there were invalid modification to the UFB.
269
270 // Convert NLIssue error messages to human-readable errors
271 $error_msgs = array(
272 NLIssue::ERROR_INVALID_REPLY_TO => "L'adresse de réponse est invalide.",
273 NLIssue::ERROR_INVALID_SHORTNAME => "Le nom court est invalide ou vide.",
274 NLIssue::ERROR_INVALID_UFC => "Le filtre des destinataires est invalide.",
275 NLIssue::ERROR_TOO_LONG_UFC => "Le nombre de matricules AX renseigné est trop élevé.",
276 NLIssue::ERROR_SQL_SAVE => "Une erreur est survenue en tentant de sauvegarder la lettre, merci de réessayer.",
277 );
278
279 // Update the current issue
280 if($aid == 'update' && Post::has('submit')) {
281
282 // Save common fields
283 $issue->title = Post::s('title');
284 $issue->title_mail = Post::s('title_mail');
285 $issue->head = Post::s('head');
286 $issue->signature = Post::s('signature');
287 $issue->reply_to = Post::s('reply_to');
288
289 if ($issue->isEditable()) {
290 // Date and shortname may only be modified for pending NLs, otherwise all links get broken.
291 $issue->date = Post::s('date');
292 $issue->shortname = strlen(Post::blank('shortname')) ? null : Post::s('shortname');
293 $issue->sufb->updateFromEnv($ufb->getEnv());
294
295 if ($nl->automaticMailingEnabled()) {
296 $issue->send_before = preg_replace('/^(\d\d\d\d)(\d\d)(\d\d)$/', '\1-\2-\3', Post::v('send_before_date')) . ' ' . Post::i('send_before_time_Hour') . ':00:00';
297 }
298 }
299 $errors = $issue->save();
300 if (count($errors)) {
301 foreach ($errors as $error_code) {
302 $page->trigError($error_msgs[$error_code]);
303 }
304 }
305 }
306
307 // Delete an article
308 if($action == 'delete') {
309 $issue->delArticle($aid);
310 pl_redirect($nl->adminPrefix(true, false) . "/edit/$nid");
311 }
312
313 // Save an article
314 if(Post::v('save')) {
315 $art = new NLArticle(Post::v('title'), Post::v('body'), Post::v('append'),
316 $aid, Post::v('cid'), Post::v('pos'));
317 $issue->saveArticle($art);
318 pl_redirect($nl->adminPrefix(true, false) . "/edit/$nid");
319 }
320
321 // Edit an article
322 if ($action == 'edit' && $aid != 'update') {
323 $eaid = $aid;
324 if (Post::has('title')) {
325 $art = new NLArticle(Post::v('title'), Post::v('body'), Post::v('append'),
326 $eaid, Post::v('cid'), Post::v('pos'));
327 } else {
328 $art = ($eaid == 'new') ? new NLArticle() : $issue->getArt($eaid);
329 }
330 if ($art && !$art->check()) {
331 $page->trigError("Cet article est trop long.");
332 }
333 $page->assign('art', $art);
334 }
335
336 // Check blacklisted IPs
337 if ($aid == 'blacklist_check') {
338 global $globals;
339 $ips_to_check = array();
340 $blacklist_host_resolution_count = 0;
341
342 foreach ($issue->arts as $key => $articles) {
343 foreach ($articles as $article) {
344 $article_ips = $article->getLinkIps($blacklist_host_resolution_count);
345 if (!empty($article_ips)) {
346 $ips_to_check[$article->title()] = $article_ips;
347 }
348 }
349 }
350
351 $page->assign('ips_to_check', $ips_to_check);
352 if ($blacklist_host_resolution_count >= $globals->mail->blacklist_host_resolution_limit) {
353 $page->trigError("Toutes les url et adresses emails de la lettre"
354 . " n'ont pas été prises en compte car la"
355 . " limite du nombre de résolutions DNS"
356 . " autorisée a été atteinte.");
357 }
358 }
359
360 if ($issue->state == NLIssue::STATE_SENT) {
361 $page->trigWarning("Cette lettre a déjà été envoyée ; il est recommandé de limiter les modifications au maximum (orthographe, adresses web et mail).");
362 }
363
364 $ufb->setEnv($issue->sufb->getEnv());
365 $page->assign_by_ref('nl', $nl);
366 $page->assign_by_ref('issue', $issue);
367 }
368
369 /** This handler will cancel the sending of the currently pending issue
370 * It is disabled for X.org mailings.
371 */
372 function handler_admin_nl_cancel($page, $nid, $force = null)
373 {
374 $nl = $this->getNl();
375 if (!$nl) {
376 return PL_NOT_FOUND;
377 }
378
379 if (!$nl->mayEdit() || !S::has_xsrf_token()) {
380 return PL_FORBIDDEN;
381 }
382
383 if (!$nid) {
384 $page->kill("La lettre n'a pas été spécifiée");
385 }
386
387 $issue = $nl->getIssue($nid);
388 if (!$issue) {
389 $page->kill("La lettre {$nid} n'existe pas.");
390 }
391 if (!$issue->cancelMailing()) {
392 $page->trigErrorRedirect("Une erreur est survenue lors de l'annulation de l'envoi.", $nl->adminPrefix());
393 }
394
395 // Logs NL cancelling.
396 S::logger()->log('nl_mailing_cancel', $nid);
397
398 $page->trigSuccessRedirect("L'envoi de l'annonce {$issue->title()} est annulé.", $nl->adminPrefix());
399 }
400
401 /** This handler will enable the sending of the currently pending issue
402 * It is disabled for X.org mailings.
403 */
404 function handler_admin_nl_valid($page, $nid, $force = null)
405 {
406 $nl = $this->getNl();
407 if (!$nl) {
408 return PL_NOT_FOUND;
409 }
410
411 if (!$nl->mayEdit() || !S::has_xsrf_token()) {
412 return PL_FORBIDDEN;
413 }
414
415 if (!$nid) {
416 $page->kill("La lettre n'a pas été spécifiée.");
417 }
418
419 $issue = $nl->getIssue($nid);
420 if (!$issue) {
421 $page->kill("La lettre {$nid} n'existe pas.");
422 }
423
424 if ($issue->isEmpty()) {
425 $page->trigErrorRedirect("La lettre étant vide, il n'est pas possible de l'envoyer.", $nl->adminPrefix());
426 }
427
428 if (!$issue->scheduleMailing()) {
429 $page->trigErrorRedirect("Une erreur est survenue lors de la validation de l'envoi.", $nl->adminPrefix());
430 }
431
432 // Logs NL validation.
433 S::logger()->log('nl_mailing_valid', $nid);
434
435 $page->trigSuccessRedirect("L'envoi de la newsletter {$issue->title()} a été validé.", $nl->adminPrefix());
436 }
437
438 /** This handler will remove the given issue.
439 */
440 function handler_admin_nl_delete($page, $nid, $force = null)
441 {
442 $nl = $this->getNl();
443 if (!$nl) {
444 return PL_NOT_FOUND;
445 }
446
447 if (!$nl->mayEdit() || !S::has_xsrf_token()) {
448 return PL_FORBIDDEN;
449 }
450
451 if (!$nid) {
452 $page->kill("La lettre n'a pas été spécifiée.");
453 }
454
455 $issue = $nl->getIssue($nid);
456 if (!$issue) {
457 $page->kill("La lettre {$nid} n'existe pas");
458 }
459 if (!$issue->isEditable()) {
460 $page->trigErrorRedirect("La lette a été envoyée ou est en cours d'envoi, elle ne peut être supprimée.", $nl->adminPrefix());
461 }
462 if (!$issue->delete()) {
463 $page->trigErrorRedirect("Une erreur est survenue lors de la suppression de la lettre.", $nl->adminPrefix());
464 }
465
466 // Logs NL deletion.
467 S::logger()->log('nl_issue_delete', $nid);
468
469 $page->trigSuccessRedirect("La lettre a bien été supprimée.", $nl->adminPrefix());
470 }
471
472 function handler_admin_nl_cat($page, $action = 'list', $id = null) {
473 $nl = $this->getNl();
474 if (!$nl) {
475 return PL_NOT_FOUND;
476 }
477
478 if (!$nl->mayEdit()) {
479 return PL_FORBIDDEN;
480 }
481
482 $page->setTitle('Administration - Newsletter : Catégories');
483 $page->assign('title', 'Gestion des catégories de la newsletter');
484 $table_editor = new PLTableEditor($nl->adminPrefix() . '/categories', 'newsletter_cat','cid');
485 $table_editor->describe('title','intitulé',true);
486 $table_editor->describe('pos','position',true);
487 if ($nl->group == Newsletter::GROUP_XORG) {
488 $table_editor->add_option_table('newsletters', 'newsletters.id = t.nlid');
489 $table_editor->add_option_field('newsletters.name', 'newsletter_name', 'Newsletter', null, 'nlid');
490 $table_editor->describe('nlid', 'ID NL', true);
491 } else {
492 $table_editor->force_field_value('nlid', $nl->id);
493 $table_editor->describe('nlid', 'nlid', false, false);
494 }
495 // Prevent deletion.
496 $table_editor->on_delete(null, null);
497 $table_editor->apply($page, $action, $id);
498 }
499
500 function handler_stat_nl($page)
501 {
502 $nl = $this->getNl();
503 if (!$nl) {
504 return PL_NOT_FOUND;
505 }
506 if (!$nl->mayEdit()) {
507 return PL_FORBIDDEN;
508 }
509
510 $page->setTitle('Statistiques - Newsletter');
511 $page->changeTpl('newsletter/statistics.tpl');
512
513 $data = array();
514 foreach (Profile::$cycles as $grade => $name) {
515 $data[$name] = array();
516 list($min, $max) = Profile::extremePromotions($grade);
517 $bound = (((int)($min / 10)) + 1) * 10;
518 while ($bound <= $max) {
519 $data[$name][$min . ' - ' . $bound] = array(
520 'count' => $nl->subscriberCount(null, null, $grade, $min, $bound),
521 'lost' => $nl->subscriberCount(true, null, $grade, $min, $bound),
522 'count_female' => $nl->subscriberCount(null, User::GENDER_FEMALE, $grade, $min, $bound),
523 'lost_female' => $nl->subscriberCount(true, User::GENDER_FEMALE, $grade, $min, $bound)
524 );
525 $min = $bound + 1;
526 $bound += 10;
527 }
528 $bound -= 9;
529 if ($bound <= $max) {
530 $data[$name][$bound . ' - ' . $max] = array(
531 'count' => $nl->subscriberCount(null, null, $grade, $bound, $max),
532 'lost' => $nl->subscriberCount(true, null, $grade, $bound, $max),
533 'count_female' => $nl->subscriberCount(null, User::GENDER_FEMALE, $grade, $bound, $max),
534 'lost_female' => $nl->subscriberCount(true, User::GENDER_FEMALE, $grade, $bound, $max)
535 );
536 }
537 }
538 $page->assign_by_ref('nl', $nl);
539 $page->assign('count', $nl->subscriberCount());
540 $page->assign('lost', $nl->lostSubscriberCount());
541 $page->assign('count_female', $nl->subscriberCount(null, User::GENDER_FEMALE));
542 $page->assign('lost_female', $nl->lostSubscriberCount(User::GENDER_FEMALE));
543 $page->assign('data', $data);
544 }
545 }
546
547 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
548 ?>