some db code rewriting
[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.ArrayList;
34 import java.util.Collections;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Locale;
40 import java.util.Map;
41
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import mir.entity.adapter.EntityAdapter;
46 import mir.entity.adapter.EntityAdapterModel;
47 import mir.entity.adapter.EntityIteratorAdapter;
48 import mir.entity.adapter.EntityAdapterEngine;
49 import mir.generator.Generator;
50 import mir.log.LoggerWrapper;
51 import mir.misc.StringUtil;
52 import mir.servlet.ServletModule;
53 import mir.servlet.ServletModuleExc;
54 import mir.servlet.ServletModuleFailure;
55 import mir.util.HTTPRequestParser;
56 import mir.util.JDBCStringRoutines;
57 import mir.util.SQLQueryBuilder;
58 import mir.util.StringRoutines;
59 import mir.util.URLBuilder;
60 import mircoders.entity.EntityContent;
61 import mircoders.entity.EntityUsers;
62 import mircoders.global.MirGlobal;
63 import mircoders.module.ModuleContent;
64 import mircoders.storage.DatabaseContent;
65 import mircoders.storage.DatabaseContentToTopics;
66
67 /**
68  * Article admin interface code
69  */
70
71 public class ServletModuleContent extends ServletModule {
72   private static ServletModuleContent instance = new ServletModuleContent();
73   public static ServletModule getInstance() { return instance; }
74   private static ModuleContent contentModule;
75
76   private ServletModuleContent() {
77     super();
78     propagatedParameters.add("selectarticleurl");
79
80     logger = new LoggerWrapper("ServletModule.Content");
81
82     try {
83       definition = "content";
84       contentModule = new ModuleContent();
85       mainModule = contentModule;
86     }
87     catch (Throwable e) {
88       logger.fatal("ServletModuleContent could not be initialized: " + e.toString());
89     }
90   }
91
92   public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
93     try {
94       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
95       SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
96       String searchField = requestParser.getParameterWithDefault("searchfield", "");
97       String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();
98       String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
99       String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
100       String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
101
102       if (searchValue.length()>0) {
103         if (searchField.equals("id"))
104           queryBuilder.appendAndCondition(
105             "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");
106         else if (searchField.equals("contents"))
107           queryBuilder.appendAndCondition(
108             "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
109             " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
110         else
111           queryBuilder.appendAndCondition(
112             "lower("+ searchField + ") like " +
113             "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
114       }
115
116       if (searchispublished.length()>0) {
117         if (searchispublished.equals("0"))
118           queryBuilder.appendAndCondition("is_published='f'");
119         else
120           queryBuilder.appendAndCondition("is_published='t'");
121       }
122
123       if (searchArticleType.length()>0) {
124         queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
125       }
126
127       if (searchOrder.length()>0) {
128         if (searchOrder.equals("datedesc"))
129           queryBuilder.appendDescendingOrder("webdb_create");
130         else if (searchOrder.equals("dateasc"))
131           queryBuilder.appendAscendingOrder("webdb_create");
132         else if (searchOrder.equals("title"))
133           queryBuilder.appendAscendingOrder("title");
134         else if (searchOrder.equals("creator"))
135           queryBuilder.appendAscendingOrder("creator");
136       }
137
138       returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);
139     }
140     catch (Throwable e) {
141       throw new ServletModuleFailure(e);
142     }
143   }
144
145   public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
146     editObject(aRequest, aResponse, null);
147   }
148
149   public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
150     try {
151       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
152
153       String now = StringUtil.date2webdbDate(new GregorianCalendar());
154       withValues.put("date", now);
155       withValues.put("publish_path", StringUtil.webdbDate2path(now));
156       withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
157       withValues.put("is_produced", "0");
158       if (!withValues.containsKey("is_published"))
159         withValues.put("is_published","0");
160       if (!withValues.containsKey("is_html"))
161         withValues.put("is_html","0");
162
163       String webdbCreate = (String) withValues.get("webdb_create");
164       if (webdbCreate==null || webdbCreate.trim().length()==0)
165         withValues.remove("webdb_create");
166
167       String id = mainModule.add(withValues);
168       logAdminUsage(aRequest, id, "object added");
169
170       DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic"));
171
172       editObject(aRequest, aResponse, id);
173     }
174     catch (Throwable e) {
175       throw new ServletModuleFailure(e);
176     }
177   }
178
179   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
180     String idParam = aRequest.getParameter("id");
181     if (idParam == null)
182       throw new ServletModuleExc("Invalid call: id not supplied ");
183     editObject(aRequest, aResponse, idParam);
184   }
185
186   /**
187    * Attaches media to an article
188    */
189   public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
190     String  mediaIdParam = aRequest.getParameter("mid");
191     String  articleId = aRequest.getParameter("articleid");
192
193     if (articleId == null || mediaIdParam==null)
194       throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");
195
196     if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId))
197       throw new ServletModuleExc("Article has been locked");
198
199     try {
200       EntityContent entContent = (EntityContent) mainModule.getById(articleId);
201       entContent.attach(mediaIdParam);
202     }
203     catch(Throwable e) {
204       throw new ServletModuleFailure(e);
205     }
206
207     logAdminUsage(aRequest, articleId, "media " + mediaIdParam + " attached");
208
209     editObject(aRequest, aResponse, articleId);
210   }
211
212   /**
213    * Deattaches media from an article
214    */
215   public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
216   {
217     String  articleId = aRequest.getParameter("articleid");
218     String  midParam = aRequest.getParameter("mid");
219     if (articleId == null)
220       throw new ServletModuleExc("smod content :: dettach :: articleid missing");
221     if (midParam == null)
222       throw new ServletModuleExc("smod content :: dettach :: mid missing");
223
224     if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId))
225       throw new ServletModuleExc("Article has been locked");
226
227     try {
228       EntityContent entContent = (EntityContent)mainModule.getById(articleId);
229       entContent.dettach(articleId, midParam);
230     }
231     catch(Throwable e) {
232       throw new ServletModuleFailure(e);
233     }
234
235     logAdminUsage(aRequest, articleId, "media " + midParam + " deattached");
236
237     editObject(aRequest, aResponse, articleId);
238   }
239
240   /**
241    * Locks an article
242    */
243   public void lock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
244   {
245     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
246
247     String idParam = requestParser.getParameter("id");
248     if (idParam == null)
249       throw new ServletModuleExc("Wrong call: (id) is missing");
250
251     EntityUsers user = ServletHelper.getUser(aRequest);
252
253     if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam))
254       throw new ServletModuleExc("Unable to lock");
255
256     contentModule.lockArticle(idParam, user.getId(), false);
257
258     editObject(aRequest, aResponse, idParam);
259   }
260
261   /**
262    * Unlocks an article
263    */
264   public void unlock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
265   {
266     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
267
268     String idParam = requestParser.getParameter("id");
269     if (idParam == null)
270       throw new ServletModuleExc("Wrong call: (id) is missing");
271
272     EntityUsers user = ServletHelper.getUser(aRequest);
273
274     if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam))
275       throw new ServletModuleExc("Unable to unlock");
276
277     contentModule.unlockArticle(idParam, user.getId(), false);
278
279     editObject(aRequest, aResponse, idParam);
280   }
281
282   /**
283    * Forcelocks an article
284    */
285   public void forcelock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
286   {
287     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
288
289     String idParam = requestParser.getParameter("id");
290     if (idParam == null)
291       throw new ServletModuleExc("Wrong call: (id) is missing");
292
293     EntityUsers user = ServletHelper.getUser(aRequest);
294
295     if (!MirGlobal.accessControl().article().mayForceLockArticle(user, idParam))
296       throw new ServletModuleExc("Unable to force lock");
297
298     contentModule.lockArticle(idParam, user.getId(), true);
299
300     editObject(aRequest, aResponse, idParam);
301   }
302
303   /**
304    * Stores an article
305    */
306   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
307   {
308     try {
309       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
310
311       String idParam = requestParser.getParameter("id");
312       if (idParam == null)
313         throw new ServletModuleExc("Wrong call: (id) is missing");
314
315       if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam))
316         throw new ServletModuleExc("Article has been locked");
317
318       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
319
320       withValues.put("is_produced", "0");
321       if (!withValues.containsKey("is_published"))
322         withValues.put("is_published","0");
323       if (!withValues.containsKey("is_html"))
324         withValues.put("is_html","0");
325
326       String webdbCreate = (String) withValues.get("webdb_create");
327       if (webdbCreate==null || webdbCreate.trim().length()==0)
328         withValues.remove("webdb_create");
329
330       String id = mainModule.set(withValues);
331
332       logAdminUsage(aRequest, id, "object modified");
333
334       DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));
335
336       if (MirGlobal.accessControl().article().mayUnlockArticle(ServletHelper.getUser(aRequest), idParam) &&
337          (requestParser.getParameterWithDefault("unlock", "0").equals("1"))) {
338         contentModule.unlockArticle(id, ServletHelper.getUser(aRequest).getId(), false);
339       }
340
341       editObject(aRequest, aResponse, idParam);
342     }
343     catch (Throwable e) {
344       throw new ServletModuleFailure(e);
345     }
346   }
347
348
349   /**
350    * Returns the basic article editing form.
351    *
352    * @param id identifier of the article. <code>null</code>, means show an
353    *     empty form to add a new article.
354    */
355   public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id)
356       throws ServletModuleExc {
357     try {
358       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
359       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
360       EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
361       Map article;
362       URLBuilder urlBuilder = new URLBuilder();
363
364       urlBuilder.setValue("module", "Content");
365       urlBuilder.setValue("do", "edit");
366       urlBuilder.setValue("id", id);
367       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
368
369       if (id!=null) {
370         responseData.put("new", Boolean.FALSE);
371         article = model.makeEntityAdapter("content", mainModule.getById(id));
372
373         EntityUsers user = ServletHelper.getUser(aRequest);
374
375         responseData.put("mayEdit", new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, id)));
376         responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, id)));
377         responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, id)));
378         responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, id)));
379       }
380       else {
381         List fields = DatabaseContent.getInstance().getFieldNames();
382         responseData.put("new", Boolean.TRUE);
383         article = new HashMap();
384         Iterator i = fields.iterator();
385         while (i.hasNext()) {
386           article.put(i.next(), null);
387         }
388
389         article.put("to_topics", null);
390
391         MirGlobal.localizer().adminInterface().initializeArticle(article);
392
393         responseData.put("mayEdit", Boolean.TRUE);
394         responseData.put("mayLock", Boolean.FALSE);
395         responseData.put("mayForceLock", Boolean.FALSE);
396         responseData.put("mayUnlock", Boolean.FALSE);
397       }
398       responseData.put("article", article);
399
400       List topicsList = new ArrayList();
401
402       String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists");
403
404       if (topicCategories.length==0 ) {
405         Map categoryMap = new HashMap();
406         categoryMap.put("key", "topic");
407         categoryMap.put("listtype", "0");
408         categoryMap.put("listparameter", "3");
409         categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", "", "title", -1, 0));
410         topicsList.add(categoryMap);
411       }
412       else {
413         for (int i = 0; i < topicCategories.length; i++) {
414           try {
415             Map categoryMap = new HashMap();
416             List parts = StringRoutines.splitString(topicCategories[i], ":");
417
418             String key = null;
419             String listtype = "0";
420             String listparameter = "5";
421             String where = "";
422             String order = "";
423
424             if (parts.size() > 0)
425               key = (String) parts.get(0);
426             if (parts.size() > 1)
427               listtype = (String) parts.get(1);
428             if (parts.size() > 2)
429               listparameter = (String) parts.get(2);
430             if (parts.size() > 3)
431               where = (String) parts.get(3);
432             if (parts.size() > 4)
433               order = (String) parts.get(4);
434
435             if (key != null) {
436               categoryMap.put("key", key);
437               categoryMap.put("listtype", listtype);
438               categoryMap.put("listparameter", listparameter);
439               categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0));
440               topicsList.add(categoryMap);
441             }
442           }
443           catch (Throwable t) {
444             logger.error("error while preparing topics: " + t.toString());
445           }
446         }
447       }
448
449       responseData.put("topics", topicsList);
450
451       responseData.put("returnurl", requestParser.getParameter("returnurl"));
452       responseData.put("thisurl", urlBuilder.getQuery());
453
454       ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
455     }
456     catch (Throwable e) {
457       throw new ServletModuleFailure(e);
458     }
459   }
460
461   public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
462     try {
463       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
464       URLBuilder urlBuilder = new URLBuilder();
465
466       urlBuilder.setValue("module", "Content");
467       urlBuilder.setValue("do", "setparent");
468       urlBuilder.setValue("childid", requestParser.getParameter("id"));
469       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
470
471       returnList(aRequest, aResponse, "", "", 0,
472           Collections.singletonMap("selectarticleurl", urlBuilder.getQuery()));
473     }
474     catch (Throwable e) {
475       throw new ServletModuleFailure(e);
476     }
477   }
478
479   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
480     try {
481       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
482       String articleId = requestParser.getParameter("article_id");
483
484       if (articleId == null)
485         throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
486
487       returnList(aRequest, aResponse, "to_content = " + articleId, "webdb_create desc", 0, null);
488     }
489     catch (Throwable e) {
490       throw new ServletModuleFailure(e);
491     }
492   }
493
494   public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
495   {
496     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
497     String articleId = requestParser.getParameter("childid");
498     String parentId  = requestParser.getParameter("id");
499     String returnUrl = requestParser.getParameter("returnurl");
500
501     if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId))
502       throw new ServletModuleExc("Article has been locked");
503
504     try {
505       EntityContent article = (EntityContent) mainModule.getById(articleId);
506       article.setFieldValue("to_content", parentId);
507       article.setProduced(false);
508       article.update();
509       logAdminUsage(aRequest, articleId, "parent set to " + parentId);
510     }
511     catch(Throwable e) {
512       logger.error("ServletModuleContent.setparent: " + e.getMessage());
513       throw new ServletModuleFailure(e);
514     }
515
516     ServletHelper.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.setFieldValue("to_content", "");
528       article.setProduced(false);
529       article.update();
530       logAdminUsage(aRequest, articleId, "parent cleared");
531     }
532     catch(Throwable e) {
533       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
534       logger.error("ServletModuleContent.clearparent: " + e.getMessage());
535
536       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
537     }
538
539     ServletHelper.redirect(aResponse, returnUrl);
540   }
541
542   public void showPreview(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
543     try {
544       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
545       String articleId = requestParser.getParameter("id");
546       EntityAdapter article = model.makeEntityAdapter("content", mainModule.getById(articleId));
547       String preview = requestParser.getParameterWithDefault("preview", "default");
548
549       Map generationValues = new HashMap();
550       Generator generator =
551           MirGlobal.localizer().adminInterface().prepareArticlePreview(preview, article, generationValues);
552
553       generator.generate(aResponse.getWriter(), generationValues, logger);
554     }
555     catch (Exception e) {
556       throw new ServletModuleFailure(e);
557     }
558   }
559 }