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