bugfix
[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  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30
31 package mircoders.servlet;
32
33 import java.util.GregorianCalendar;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Locale;
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.util.CachingRewindableIterator;
52 import mir.util.HTTPRequestParser;
53 import mir.util.JDBCStringRoutines;
54 import mir.util.SQLQueryBuilder;
55 import mir.util.URLBuilder;
56 import mircoders.entity.EntityContent;
57 import mircoders.entity.EntityUsers;
58 import mircoders.global.MirGlobal;
59 import mircoders.module.ModuleContent;
60 import mircoders.search.IndexUtil;
61 import mircoders.storage.DatabaseComment;
62 import mircoders.storage.DatabaseContent;
63 import mircoders.storage.DatabaseContentToMedia;
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.52.2.3 2003/06/19 22:57:34 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("id"))
128           queryBuilder.appendAndCondition(
129             "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");
130         else if (searchField.equals("contents"))
131           queryBuilder.appendAndCondition(
132             "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
133             " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
134         else
135           queryBuilder.appendAndCondition(
136             "lower("+ searchField + ") like " +
137             "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
138       }
139
140       if (searchispublished.length()>0) {
141         if (searchispublished.equals("0"))
142           queryBuilder.appendAndCondition("is_published='f'");
143         else
144           queryBuilder.appendAndCondition("is_published='t'");
145       }
146
147       if (searchArticleType.length()>0) {
148         queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
149       }
150
151       if (searchOrder.length()>0) {
152         if (searchOrder.equals("datedesc"))
153           queryBuilder.appendAscendingOrder("webdb_create");
154         else if (searchOrder.equals("dateasc"))
155           queryBuilder.appendDescendingOrder("webdb_create");
156         else if (searchOrder.equals("title"))
157           queryBuilder.appendDescendingOrder("title");
158         else if (searchOrder.equals("creator"))
159           queryBuilder.appendDescendingOrder("creator");
160       }
161
162       returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
163     }
164     catch (Throwable e) {
165       throw new ServletModuleFailure(e);
166     }
167   }
168
169   public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
170     _showObject(null, aRequest, aResponse);
171   }
172
173
174   public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
175   {
176 //theLog.printDebugInfo(":: content :: trying to insert");
177     try {
178       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
179
180       String now = StringUtil.date2webdbDate(new GregorianCalendar());
181       withValues.put("date", now);
182       withValues.put("publish_path", StringUtil.webdbDate2path(now));
183       withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
184       withValues.put("is_produced", "0");
185       if (!withValues.containsKey("is_published"))
186         withValues.put("is_published","0");
187       if (!withValues.containsKey("is_html"))
188         withValues.put("is_html","0");
189
190       String webdbCreate = (String) withValues.get("webdb_create");
191       if (webdbCreate==null || webdbCreate.trim().length()==0)
192         withValues.remove("webdb_create");
193
194       String id = mainModule.add(withValues);
195       List topics;
196
197       DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic"));
198
199       _showObject(id, aRequest, aResponse);
200     }
201     catch (Throwable e) {
202       throw new ServletModuleFailure(e);
203     }
204   }
205
206   public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
207   {
208     if (!configuration.getString("Mir.Localizer.Admin.AllowDeleteArticle", "0").equals("1"))
209       throw new ServletModuleExc("Operation not permitted");
210
211     String idParam = aRequest.getParameter("id");
212     if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");
213
214     String confirmParam = aRequest.getParameter("confirm");
215     String cancelParam = aRequest.getParameter("cancel");
216
217     logger.info("where = " + aRequest.getParameter("where"));
218
219     if (confirmParam == null && cancelParam == null) {
220
221       SimpleHash mergeData = new SimpleHash();
222       mergeData.put("module", "Content");
223       mergeData.put("infoString", "Content: " + idParam);
224       mergeData.put("id", idParam);
225       mergeData.put("where", aRequest.getParameter("where"));
226       mergeData.put("order", aRequest.getParameter("order"));
227       mergeData.put("offset", aRequest.getParameter("offset"));
228       deliver(aRequest, aResponse, mergeData, templateConfirmString);
229     }
230     else {
231       if (confirmParam!= null && !confirmParam.equals("")) {
232         try {
233           mainModule.deleteById(idParam);
234
235           /** @todo the following two should be implied in
236            *  DatabaseContent */
237           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
238           DatabaseComment.getInstance().deleteByContentId(idParam);
239           DatabaseContentToMedia.getInstance().deleteByContentId(idParam);
240
241
242           //delete from lucene index, if any
243           String index = configuration.getString("IndexPath");
244           if (IndexReader.indexExists(index)){
245             IndexUtil.unindexID(idParam,index);
246           }
247
248         }
249         catch (Throwable e) {
250           throw new ServletModuleFailure(e);
251         }
252         list(aRequest,aResponse);
253       }
254       else {
255         // Datensatz anzeigen
256         _showObject(idParam, aRequest, aResponse);
257       }
258     }
259   }
260
261   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
262   {
263     String idParam = aRequest.getParameter("id");
264     if (idParam == null)
265       throw new ServletModuleExc("Invalid call: id not supplied ");
266     _showObject(idParam, aRequest, aResponse);
267   }
268
269 // methods for attaching media file
270   public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
271   {
272     String  mediaIdParam = aRequest.getParameter("mid");
273     String  articleId = aRequest.getParameter("articleid");
274
275     if (articleId == null || mediaIdParam==null)
276       throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");
277
278     try {
279       EntityContent entContent = (EntityContent) mainModule.getById(articleId);
280       entContent.attach(mediaIdParam);
281     }
282     catch(Throwable e) {
283       throw new ServletModuleFailure(e);
284     }
285
286     _showObject(articleId, aRequest, aResponse);
287   }
288
289   public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
290   {
291     String  articleId = aRequest.getParameter("articleid");
292     String  midParam = aRequest.getParameter("mid");
293     if (articleId == null)
294       throw new ServletModuleExc("smod content :: dettach :: articleid missing");
295     if (midParam == null)
296       throw new ServletModuleExc("smod content :: dettach :: mid missing");
297
298     try {
299       EntityContent entContent = (EntityContent)mainModule.getById(articleId);
300       entContent.dettach(articleId, midParam);
301     }
302     catch(Throwable e) {
303       throw new ServletModuleFailure(e);
304     }
305
306     _showObject(articleId, aRequest, aResponse);
307   }
308
309   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
310   {
311     try {
312       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
313
314       String returnUrl = requestParser.getParameter("returnurl");
315
316       String idParam = aRequest.getParameter("id");
317       if (idParam == null)
318         throw new ServletModuleExc("Wrong call: (id) is missing");
319
320       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
321
322       String content_id = aRequest.getParameter("id");
323
324       withValues.put("is_produced", "0");
325       if (!withValues.containsKey("is_published"))
326         withValues.put("is_published","0");
327       if (!withValues.containsKey("is_html"))
328         withValues.put("is_html","0");
329
330       String webdbCreate = (String) withValues.get("webdb_create");
331       if (webdbCreate==null || webdbCreate.trim().length()==0)
332         withValues.remove("webdb_create");
333
334       String id = mainModule.set(withValues);
335       DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));
336
337       String whereParam = aRequest.getParameter("where");
338       String orderParam = aRequest.getParameter("order");
339
340       if (returnUrl!=null){
341         redirect(aResponse, returnUrl);
342       }
343       else
344         _showObject(idParam, aRequest, aResponse);
345     }
346     catch (Throwable e) {
347       throw new ServletModuleFailure(e);
348     }
349   }
350
351
352   /**
353    * HelperMethod shows the basic article editing form.
354    *
355    * if the "id" parameter is null, it means show an empty form to add a new
356    * article.
357    *
358    * @param id
359    * @param aRequest
360    * @param aResponse
361    * @throws ServletModuleExc
362    */
363   public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)
364       throws ServletModuleExc {
365     try {
366       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
367       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
368       EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
369       Map article;
370       URLBuilder urlBuilder = new URLBuilder();
371
372       urlBuilder.setValue("module", "Content");
373       urlBuilder.setValue("do", "edit");
374       urlBuilder.setValue("id", id);
375       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
376
377       if (id!=null) {
378         responseData.put("new", Boolean.FALSE);
379         article = model.makeEntityAdapter("content", mainModule.getById(id));
380       }
381       else {
382         List fields = DatabaseContent.getInstance().getFields();
383         responseData.put("new", Boolean.TRUE);
384         article = new HashMap();
385         Iterator i = fields.iterator();
386         while (i.hasNext()) {
387           article.put(i.next(), null);
388         }
389
390         article.put("to_topics", null);
391
392         MirGlobal.localizer().adminInterface().initializeArticle(article);
393       }
394       responseData.put("article", article);
395
396       responseData.put("topics",
397           new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"),
398           20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
399
400       responseData.put("returnurl", requestParser.getParameter("returnurl"));
401       responseData.put("thisurl", urlBuilder.getQuery());
402
403       ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
404     }
405     catch (Throwable e) {
406       throw new ServletModuleFailure(e);
407     }
408   }
409
410   public void returnArticleList(
411        HttpServletRequest aRequest,
412        HttpServletResponse aResponse,
413        String aWhereClause,
414        String anOrderByClause,
415        int anOffset,
416        String aSelectArticleUrl) throws ServletModuleExc {
417
418     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
419     URLBuilder urlBuilder = new URLBuilder();
420     EntityAdapterModel model;
421     int nrArticlesPerPage = 20;
422     int count;
423
424     try {
425       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
426       model = MirGlobal.localizer().dataModel().adapterModel();
427
428       Object articleList =
429           new CachingRewindableIterator(
430             new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
431                MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
432       );
433
434       responseData.put("nexturl", null);
435       responseData.put("prevurl", null);
436
437       count=mainModule.getSize(aWhereClause);
438
439       urlBuilder.setValue("module", "Content");
440       urlBuilder.setValue("do", "list");
441       urlBuilder.setValue("where", aWhereClause);
442       urlBuilder.setValue("order", anOrderByClause);
443
444
445       urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
446       urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
447       urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
448       urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
449       urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
450       urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
451
452       responseData.put("searchfield", requestParser.getParameter("searchfield"));
453       responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
454       responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
455       responseData.put("searchorder", requestParser.getParameter("searchorder"));
456       responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
457       responseData.put("selectarticleurl", aSelectArticleUrl);
458
459       urlBuilder.setValue("offset", anOffset);
460       responseData.put("offset" , new Integer(anOffset).toString());
461       responseData.put("thisurl" , urlBuilder.getQuery());
462
463       if (count>=anOffset+nrArticlesPerPage) {
464         urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
465         responseData.put("nexturl" , urlBuilder.getQuery());
466       }
467
468       if (anOffset>0) {
469         urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));
470         responseData.put("prevurl" , urlBuilder.getQuery());
471       }
472
473       responseData.put("articles", articleList);
474
475       responseData.put("from" , Integer.toString(anOffset+1));
476       responseData.put("count", Integer.toString(count));
477       responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
478       responseData.put("offset" , Integer.toString(anOffset));
479       responseData.put("order", anOrderByClause);
480       responseData.put("where" , aWhereClause);
481
482       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
483     }
484     catch (Throwable e) {
485       throw new ServletModuleFailure(e);
486     }
487   }
488
489   public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
490   {
491     try {
492       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
493       URLBuilder urlBuilder = new URLBuilder();
494
495       urlBuilder.setValue("module", "Content");
496       urlBuilder.setValue("do", "setparent");
497       urlBuilder.setValue("childid", requestParser.getParameter("id"));
498       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
499
500       returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
501     }
502     catch (Throwable e) {
503       throw new ServletModuleFailure(e);
504     }
505   }
506
507   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
508   {
509     try {
510       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
511       String articleId = requestParser.getParameter("article_id");
512
513       if (articleId == null)
514         throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
515
516       returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
517     }
518     catch (Throwable e) {
519       throw new ServletModuleFailure(e);
520     }
521   }
522
523   public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
524   {
525     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
526     String articleId = aRequest.getParameter("childid");
527     String parentId  = aRequest.getParameter("id");
528     String returnUrl = aRequest.getParameter("returnurl");
529
530     try {
531       EntityContent article = (EntityContent) mainModule.getById(articleId);
532       article.setValueForProperty("to_content", parentId);
533       article.setProduced(false);
534       article.update();
535     }
536     catch(Throwable e) {
537       logger.error("ServletModuleContent.setparent: " + e.getMessage());
538       throw new ServletModuleFailure(e);
539     }
540
541     redirect(aResponse, returnUrl);
542   }
543
544   public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
545   {
546     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
547     String articleId = requestParser.getParameter("id");
548     String returnUrl = requestParser.getParameter("returnurl");
549
550     try {
551       EntityContent article = (EntityContent) mainModule.getById(articleId);
552       article.setValueForProperty("to_content", "");
553       article.setProduced(false);
554       article.update();
555     }
556     catch(Throwable e) {
557       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
558       logger.error("ServletModuleContent.clearparent: " + e.getMessage());
559
560       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
561     }
562
563     redirect(aResponse, returnUrl);
564   }
565 }