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