- topiclist now optionally with checkboxes on article edit form
[mir.git] / source / mircoders / servlet / ServletModuleContent.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir 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  * Mir 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 Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.servlet;
33
34 import java.util.GregorianCalendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import javax.servlet.http.HttpSession;
43
44 import mir.entity.adapter.EntityAdapterModel;
45 import mir.entity.adapter.EntityIteratorAdapter;
46 import mir.log.LoggerWrapper;
47 import mir.misc.StringUtil;
48 import mir.servlet.ServletModule;
49 import mir.servlet.ServletModuleExc;
50 import mir.servlet.ServletModuleFailure;
51 import mir.storage.StorageObjectFailure;
52 import mir.util.CachingRewindableIterator;
53 import mir.util.HTTPRequestParser;
54 import mir.util.JDBCStringRoutines;
55 import mir.util.SQLQueryBuilder;
56 import mir.util.URLBuilder;
57 import mircoders.entity.EntityContent;
58 import mircoders.entity.EntityUsers;
59 import mircoders.global.MirGlobal;
60 import mircoders.module.ModuleContent;
61 import mircoders.search.IndexUtil;
62 import mircoders.storage.DatabaseComment;
63 import mircoders.storage.DatabaseContent;
64 import mircoders.storage.DatabaseContentToTopics;
65
66 import org.apache.lucene.index.IndexReader;
67
68 import freemarker.template.SimpleHash;
69
70 /*
71  *  ServletModuleContent -
72  *  deliver html for the article admin form.
73  *
74  * @version $Id: ServletModuleContent.java,v 1.45 2003/03/16 00:11:09 zapata Exp $
75  * @author rk, mir-coders
76  *
77  */
78
79 public class ServletModuleContent extends ServletModule
80 {
81   private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;
82   private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");
83
84   private static ServletModuleContent instance = new ServletModuleContent();
85   public static ServletModule getInstance() { return instance; }
86
87   private ServletModuleContent() {
88     super();
89     logger = new LoggerWrapper("ServletModule.Content");
90     try {
91
92       templateListString = configuration.getString("ServletModule.Content.ListTemplate");
93       templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");
94       templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");
95
96       mainModule = new ModuleContent(DatabaseContent.getInstance());
97     }
98     catch (Throwable e) {
99       logger.fatal("ServletModuleContent could not be initialized: " + e.toString());
100     }
101   }
102
103   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
104   {
105     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
106
107     String where = requestParser.getParameter("where");
108     String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
109     int offset = requestParser.getIntegerWithDefault("offset", 0);
110     String selectArticleUrl = requestParser.getParameter("selectarticleurl");
111
112     returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl);
113   }
114
115   public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
116     try {
117       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
118       SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
119       String searchField = requestParser.getParameterWithDefault("searchfield", "");
120       String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();
121       String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
122       String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
123       String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
124       String selectArticleUrl = requestParser.getParameter("selectarticleurl");
125
126       if (searchValue.length()>0) {
127         if (searchField.equals("contents"))
128           queryBuilder.appendAndCondition(
129             "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
130             " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
131         else
132           queryBuilder.appendAndCondition(
133             "lower("+ searchField + ") like " +
134             "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
135       }
136
137       if (searchispublished.length()>0) {
138         if (searchispublished.equals("0"))
139           queryBuilder.appendAndCondition("is_published='f'");
140         else
141           queryBuilder.appendAndCondition("is_published='t'");
142       }
143
144       if (searchArticleType.length()>0) {
145         queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
146       }
147
148       if (searchOrder.length()>0) {
149         if (searchOrder.equals("datedesc"))
150           queryBuilder.appendAscendingOrder("webdb_create");
151         else if (searchOrder.equals("dateasc"))
152           queryBuilder.appendDescendingOrder("webdb_create");
153         else if (searchOrder.equals("title"))
154           queryBuilder.appendDescendingOrder("title");
155         else if (searchOrder.equals("creator"))
156           queryBuilder.appendDescendingOrder("creator");
157       }
158
159       returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
160     }
161     catch (Throwable e) {
162       throw new ServletModuleFailure(e);
163     }
164   }
165
166   public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
167     _showObject(null, req, res);
168   }
169
170
171   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
172   {
173 //theLog.printDebugInfo(":: content :: trying to insert");
174     try {
175       EntityUsers   user = _getUser(req);
176       Map withValues = getIntersectingValues(req, DatabaseContent.getInstance());
177
178       String now = StringUtil.date2webdbDate(new GregorianCalendar());
179       withValues.put("date", now);
180       withValues.put("publish_path", StringUtil.webdbDate2path(now));
181       withValues.put("to_publisher", user.getId());
182       withValues.put("is_produced", "0");
183       if (!withValues.containsKey("is_published"))
184         withValues.put("is_published","0");
185       if (!withValues.containsKey("is_html"))
186         withValues.put("is_html","0");
187
188       String id = mainModule.add(withValues);
189       DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
190
191       _showObject(id, req, res);
192     }
193     catch (Throwable e) {
194       throw new ServletModuleFailure(e);
195     }
196   }
197
198   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
199   {
200     EntityUsers   user = _getUser(req);
201
202     String idParam = req.getParameter("id");
203     if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");
204
205     String confirmParam = req.getParameter("confirm");
206     String cancelParam = req.getParameter("cancel");
207
208     logger.info("where = " + req.getParameter("where"));
209
210     if (confirmParam == null && cancelParam == null) {
211
212       SimpleHash mergeData = new SimpleHash();
213       mergeData.put("module", "Content");
214       mergeData.put("infoString", "Content: " + idParam);
215       mergeData.put("id", idParam);
216       mergeData.put("where", req.getParameter("where"));
217       mergeData.put("order", req.getParameter("order"));
218       mergeData.put("offset", req.getParameter("offset"));
219       deliver(req, res, mergeData, templateConfirmString);
220     }
221     else {
222       if (confirmParam!= null && !confirmParam.equals("")) {
223         try {
224           mainModule.deleteById(idParam);
225
226           /** @todo the following two should be implied in
227            *  DatabaseContent */
228
229           //delete rows in the content_x_topic-table
230           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
231           //delete rows in the comment-table
232           DatabaseComment.getInstance().deleteByContentId(idParam);
233           //delete from lucene index, if any
234           String index = configuration.getString("IndexPath");
235           if (IndexReader.indexExists(index)){
236             IndexUtil.unindexID(idParam,index);
237           }
238
239         }
240         catch (Throwable e) {
241           throw new ServletModuleFailure(e);
242         }
243         list(req,res);
244       }
245       else {
246         // Datensatz anzeigen
247         _showObject(idParam, req, res);
248       }
249     }
250   }
251
252   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
253   {
254     String idParam = req.getParameter("id");
255     if (idParam == null)
256       throw new ServletModuleExc("Invalid call: id not supplied ");
257     _showObject(idParam, req, res);
258   }
259
260 // methods for attaching media file
261   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
262   {
263     String  mediaIdParam = req.getParameter("mid");
264     String  idParam = req.getParameter("cid");
265     if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing");
266
267     try {
268       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
269       entContent.attach(mediaIdParam);
270     }
271     catch(Throwable e) {
272       logger.error("smod content :: attach :: could not get entityContent");
273     }
274
275     _showObject(idParam, req, res);
276   }
277
278   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
279   {
280     String  cidParam = req.getParameter("cid");
281     String  midParam = req.getParameter("mid");
282     if (cidParam == null)
283       throw new ServletModuleExc("smod content :: dettach :: cid missing");
284     if (midParam == null)
285       throw new ServletModuleExc("smod content :: dettach :: mid missing");
286
287     try {
288       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
289       entContent.dettach(cidParam,midParam);
290     }
291     catch(Throwable e) {
292       logger.error("smod content :: dettach :: could not get entityContent");
293     }
294
295     _showObject(cidParam, req, res);
296   }
297
298   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
299   {
300     try {
301       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
302
303       String returnUrl = requestParser.getParameter("returnurl");
304
305       String idParam = aRequest.getParameter("id");
306       if (idParam == null)
307         throw new ServletModuleExc("Wrong call: (id) is missing");
308
309       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
310       String[] topic_id = aRequest.getParameterValues("to_topic");
311       String content_id = aRequest.getParameter("id");
312
313       withValues.put("is_produced", "0");
314       if (!withValues.containsKey("is_published"))
315         withValues.put("is_published","0");
316       if (!withValues.containsKey("is_html"))
317         withValues.put("is_html","0");
318
319       String id = mainModule.set(withValues);
320       DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id);
321
322       String whereParam = aRequest.getParameter("where");
323       String orderParam = aRequest.getParameter("order");
324
325       if (returnUrl!=null){
326         redirect(aResponse, returnUrl);
327       }
328       else
329         _showObject(idParam, aRequest, aResponse);
330     }
331     catch (Throwable e) {
332       throw new ServletModuleFailure(e);
333     }
334   }
335
336 /*
337   * HelperMethod shows the basic article editing form.
338   *
339   * if the "id" parameter is null, it means show an empty form to add a new
340   * article.
341 */
342   public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)
343       throws ServletModuleExc {
344     try {
345       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
346       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
347       EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
348       Map article;
349       URLBuilder urlBuilder = new URLBuilder();
350
351       urlBuilder.setValue("module", "Content");
352       urlBuilder.setValue("do", "edit");
353       urlBuilder.setValue("id", id);
354       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
355
356       if (id!=null) {
357         responseData.put("new", Boolean.FALSE);
358         article = model.makeEntityAdapter("content", mainModule.getById(id));
359       }
360       else {
361         List fields = DatabaseContent.getInstance().getFields();
362         responseData.put("new", Boolean.TRUE);
363         article = new HashMap();
364         Iterator i = fields.iterator();
365         while (i.hasNext()) {
366           article.put(i.next(), null);
367         }
368
369         article.put("to_topics", null);
370
371         MirGlobal.localizer().adminInterface().initializeArticle(article);
372       }
373       responseData.put("article", article);
374
375       responseData.put("topics",
376           new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"),
377           20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
378
379
380
381       responseData.put("returnurl", requestParser.getParameter("returnurl"));
382       responseData.put("thisurl", urlBuilder.getQuery());
383
384       ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
385     }
386     catch (Throwable e) {
387       throw new ServletModuleFailure(e);
388     }
389   }
390
391   public void returnArticleList(
392        HttpServletRequest aRequest,
393        HttpServletResponse aResponse,
394        String aWhereClause,
395        String anOrderByClause,
396        int anOffset,
397        String aSelectArticleUrl) throws ServletModuleExc {
398
399     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
400     URLBuilder urlBuilder = new URLBuilder();
401     EntityAdapterModel model;
402     int nrArticlesPerPage = 20;
403     int count;
404
405     try {
406       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
407       model = MirGlobal.localizer().dataModel().adapterModel();
408
409       Object articleList =
410           new CachingRewindableIterator(
411             new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
412                MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
413       );
414
415       responseData.put("nexturl", null);
416       responseData.put("prevurl", null);
417
418       count=mainModule.getSize(aWhereClause);
419
420       urlBuilder.setValue("module", "Content");
421       urlBuilder.setValue("do", "list");
422       urlBuilder.setValue("where", aWhereClause);
423       urlBuilder.setValue("order", anOrderByClause);
424
425
426       urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
427       urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
428       urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
429       urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
430       urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
431       urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
432
433       responseData.put("searchfield", requestParser.getParameter("searchfield"));
434       responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
435       responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
436       responseData.put("searchorder", requestParser.getParameter("searchorder"));
437       responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
438       responseData.put("selectarticleurl", aSelectArticleUrl);
439
440       urlBuilder.setValue("offset", anOffset);
441       responseData.put("offset" , new Integer(anOffset).toString());
442       responseData.put("thisurl" , urlBuilder.getQuery());
443
444       if (count>=anOffset+nrArticlesPerPage) {
445         urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
446         responseData.put("nexturl" , urlBuilder.getQuery());
447       }
448
449       if (anOffset>0) {
450         urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));
451         responseData.put("prevurl" , urlBuilder.getQuery());
452       }
453
454       responseData.put("articles", articleList);
455
456       responseData.put("from" , Integer.toString(anOffset+1));
457       responseData.put("count", Integer.toString(count));
458       responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
459       responseData.put("offset" , Integer.toString(anOffset));
460       responseData.put("order", anOrderByClause);
461       responseData.put("where" , aWhereClause);
462
463       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
464     }
465     catch (Throwable e) {
466       throw new ServletModuleFailure(e);
467     }
468   }
469
470   public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
471   {
472     try {
473       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
474       URLBuilder urlBuilder = new URLBuilder();
475
476       urlBuilder.setValue("module", "Content");
477       urlBuilder.setValue("do", "setparent");
478       urlBuilder.setValue("childid", requestParser.getParameter("id"));
479       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
480
481       returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
482     }
483     catch (Throwable e) {
484       throw new ServletModuleFailure(e);
485     }
486   }
487
488   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
489   {
490     try {
491       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
492       String articleId = requestParser.getParameter("article_id");
493
494       if (articleId == null)
495         throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
496
497       returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
498     }
499     catch (Throwable e) {
500       throw new ServletModuleFailure(e);
501     }
502   }
503
504   public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
505   {
506     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
507     String articleId = aRequest.getParameter("childid");
508     String parentId  = aRequest.getParameter("id");
509     String returnUrl = aRequest.getParameter("returnurl");
510
511     try {
512       EntityContent article = (EntityContent) mainModule.getById(articleId);
513       article.setValueForProperty("to_content", parentId);
514       article.setProduced(false);
515       article.update();
516     }
517     catch(Throwable e) {
518       logger.error("ServletModuleContent.setparent: " + e.getMessage());
519       throw new ServletModuleFailure(e);
520     }
521
522     redirect(aResponse, returnUrl);
523   }
524
525   public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
526   {
527     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
528     String articleId = requestParser.getParameter("id");
529     String returnUrl = requestParser.getParameter("returnurl");
530
531     try {
532       EntityContent article = (EntityContent) mainModule.getById(articleId);
533       article.setValueForProperty("to_content", "");
534       article.setProduced(false);
535       article.update();
536     }
537     catch(Throwable e) {
538       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
539       logger.error("ServletModuleContent.clearparent: " + e.getMessage());
540
541       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
542     }
543
544     redirect(aResponse, returnUrl);
545   }
546
547   private EntityUsers _getUser(HttpServletRequest req)
548   {
549     HttpSession session=req.getSession(false);
550
551     return (EntityUsers)session.getAttribute("login.uid");
552   }
553 }