bb666740def4843eca0fca1a4207652372201c98
[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.43 2003/03/09 19:14:21 idfx 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 (StorageObjectFailure e) {
99       logger.error("servletmodulecontent konnte nicht initialisiert werden");
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("returnurl", requestParser.getParameter("returnurl"));
376       responseData.put("thisurl", urlBuilder.getQuery());
377
378       ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
379     }
380     catch (Throwable e) {
381       throw new ServletModuleFailure(e);
382     }
383   }
384
385   public void returnArticleList(
386        HttpServletRequest aRequest,
387        HttpServletResponse aResponse,
388        String aWhereClause,
389        String anOrderByClause,
390        int anOffset,
391        String aSelectArticleUrl) throws ServletModuleExc {
392
393     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
394     URLBuilder urlBuilder = new URLBuilder();
395     EntityAdapterModel model;
396     int nrArticlesPerPage = 20;
397     int count;
398
399     try {
400       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
401       model = MirGlobal.localizer().dataModel().adapterModel();
402
403       Object articleList =
404           new CachingRewindableIterator(
405             new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
406                MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
407       );
408
409       responseData.put("nexturl", null);
410       responseData.put("prevurl", null);
411
412       count=mainModule.getSize(aWhereClause);
413
414       urlBuilder.setValue("module", "Content");
415       urlBuilder.setValue("do", "list");
416       urlBuilder.setValue("where", aWhereClause);
417       urlBuilder.setValue("order", anOrderByClause);
418
419
420       urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
421       urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
422       urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
423       urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
424       urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
425       urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
426
427       responseData.put("searchfield", requestParser.getParameter("searchfield"));
428       responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
429       responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
430       responseData.put("searchorder", requestParser.getParameter("searchorder"));
431       responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
432       responseData.put("selectarticleurl", aSelectArticleUrl);
433
434       urlBuilder.setValue("offset", anOffset);
435       responseData.put("offset" , new Integer(anOffset).toString());
436       responseData.put("thisurl" , urlBuilder.getQuery());
437
438       if (count>=anOffset+nrArticlesPerPage) {
439         urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
440         responseData.put("nexturl" , urlBuilder.getQuery());
441       }
442
443       if (anOffset>0) {
444         urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));
445         responseData.put("prevurl" , urlBuilder.getQuery());
446       }
447
448       responseData.put("articles", articleList);
449
450       responseData.put("from" , Integer.toString(anOffset+1));
451       responseData.put("count", Integer.toString(count));
452       responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
453       responseData.put("offset" , Integer.toString(anOffset));
454       responseData.put("order", anOrderByClause);
455       responseData.put("where" , aWhereClause);
456
457       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
458     }
459     catch (Throwable e) {
460       throw new ServletModuleFailure(e);
461     }
462   }
463
464   public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
465   {
466     try {
467       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
468       URLBuilder urlBuilder = new URLBuilder();
469
470       urlBuilder.setValue("module", "Content");
471       urlBuilder.setValue("do", "setparent");
472       urlBuilder.setValue("childid", requestParser.getParameter("id"));
473       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
474
475       returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
476     }
477     catch (Throwable e) {
478       throw new ServletModuleFailure(e);
479     }
480   }
481
482   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
483   {
484     try {
485       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
486       String articleId = requestParser.getParameter("article_id");
487
488       if (articleId == null)
489         throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
490
491       returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
492     }
493     catch (Throwable e) {
494       throw new ServletModuleFailure(e);
495     }
496   }
497
498   public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
499   {
500     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
501     String articleId = aRequest.getParameter("childid");
502     String parentId  = aRequest.getParameter("id");
503     String returnUrl = aRequest.getParameter("returnurl");
504
505     try {
506       EntityContent article = (EntityContent) mainModule.getById(articleId);
507       article.setValueForProperty("to_content", parentId);
508       article.setProduced(false);
509       article.update();
510     }
511     catch(Throwable e) {
512       logger.error("ServletModuleContent.setparent: " + e.getMessage());
513       throw new ServletModuleFailure(e);
514     }
515
516     redirect(aResponse, returnUrl);
517   }
518
519   public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
520   {
521     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
522     String articleId = requestParser.getParameter("id");
523     String returnUrl = requestParser.getParameter("returnurl");
524
525     try {
526       EntityContent article = (EntityContent) mainModule.getById(articleId);
527       article.setValueForProperty("to_content", "");
528       article.setProduced(false);
529       article.update();
530     }
531     catch(Throwable e) {
532       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
533       logger.error("ServletModuleContent.clearparent: " + e.getMessage());
534
535       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
536     }
537
538     redirect(aResponse, returnUrl);
539   }
540
541   private EntityUsers _getUser(HttpServletRequest req)
542   {
543     HttpSession session=req.getSession(false);
544
545     return (EntityUsers)session.getAttribute("login.uid");
546   }
547 }