Mir goes GPL
[mir.git] / source / mircoders / entity / EntityContent.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.entity;
33
34 import java.lang.*;
35 import java.io.*;
36 import java.util.*;
37 import java.sql.*;
38 import java.lang.reflect.*;
39
40 import freemarker.template.*;
41
42 import mir.entity.*;
43 import mir.misc.*;
44 import mir.media.*;
45 import mir.storage.*;
46
47 import mircoders.storage.*;
48
49 /**
50  * this class implements mapping of one line of the database table content
51  * to a java object
52  *
53  * @version $Revision: 1.9.2.1 $ $Date: 2002/09/01 21:31:43 $
54  * @author $Author: mh $
55  *
56  * $Log: EntityContent.java,v $
57  * Revision 1.9.2.1  2002/09/01 21:31:43  mh
58  * Mir goes GPL
59  *
60  * Revision 1.9  2002/07/19 20:55:49  mh
61  * commented out decodeHTML, as we don't encodeHTML anymore
62  *
63  * Revision 1.8  2002/06/28 20:37:33  mh
64  * make date_formatted be webdb_create_short instead to be more consistent. also make date2webdb.. use webdb_create
65  *
66  * 
67  */
68
69
70 public class EntityContent extends Entity
71 {
72
73   String mirconf_extLinkName  = MirConfig.getProp("Producer.ExtLinkName");
74   String mirconf_intLinkName  = MirConfig.getProp("Producer.IntLinkName");
75   String mirconf_mailLinkName = MirConfig.getProp("Producer.MailLinkName");
76   String mirconf_imageRoot    = MirConfig.getProp("Producer.ImageRoot");
77
78   //this should always be transient i.e it can never be stored in the db
79   //or ObjectStore. (so the ObjectStore should only be caching what comes
80   //directly out of the DB. @todo confirm this with rk. -mh
81   HashMap _entCache = new HashMap();
82   Boolean _hasMedia = null;
83
84         // constructors
85
86         public EntityContent()
87         {
88                 super();
89     //content_data is now filed-type "text"
90                 //streamedInput = new ArrayList();
91                 //streamedInput.add("content_data");
92         }
93
94         public EntityContent(StorageObject theStorage) {
95                 this();
96                 setStorage(theStorage);
97         }
98
99         //
100         // methods
101
102  /**
103         * set is_produced flag for the article
104         */
105
106         public void setProduced(boolean yesno) throws StorageObjectException
107         {
108                 String value = (yesno) ? "1":"0";
109                 if (value.equals( getValue("is_produced") )) return;
110
111     Connection con=null;Statement stmt=null;
112     String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
113                 try {
114                         con = theStorageObject.getPooledCon();
115                         /** @todo should be preparedStatement: faster!! */
116                         stmt = con.createStatement();
117                         theStorageObject.executeUpdate(stmt,sql);
118                 } catch (StorageObjectException e) {
119             throwStorageObjectException(e, "\n -- set produced failed");
120                 } catch (SQLException e) {
121             throwStorageObjectException(e, "\n -- set produced failed");
122                 } finally {
123                         theStorageObject.freeConnection(con,stmt);
124                 }
125         }
126
127
128  /**
129         * make openposting to newswire
130         */
131
132         public void newswire() throws StorageObjectException
133         {
134                 String sql = "update content set to_article_type='1', is_produced='0' where id='" + getId()+"'";
135                 try {
136                                 theStorageObject.executeUpdate(sql);
137                 } catch (StorageObjectException e) {
138             throwStorageObjectException(e, "\n -- newswire failed");
139                 } catch (SQLException e) {
140             throwStorageObjectException(e, "\n -- newswire failed");
141                 }
142         }
143
144
145  /**
146         * dettach from media
147         */
148         public void dettach(String cid,String mid) throws StorageObjectException
149         {
150                 if (mid!=null){
151                         try{
152                                 DatabaseContentToMedia.getInstance().delete(cid,mid);
153                         } catch (Exception e){
154                 throwStorageObjectException(e, "\n -- failed to get instance");
155                         }
156                         //set Content to unproduced
157                         setProduced(false);
158                 }
159         }
160
161  /**
162         * attach to media
163         */
164
165         public void attach(String mid) throws StorageObjectException
166         {
167                 if (mid!=null) {
168                         //write media-id mid and content-id in table content_x_media
169                         try{
170                                 DatabaseContentToMedia.getInstance().addMedia(getId(),mid);
171                         } catch(StorageObjectException e){
172                                 throwStorageObjectException(e, "attach: could not get the instance");
173                         }
174                         //set Content to unproduced
175                         setProduced(false);
176                 }       else {
177                         theLog.printError("EntityContent: attach without mid");
178                 }
179         }
180
181         /**
182          * overridden method getValue to include formatted date into every
183          * entityContent
184          */
185
186         public String getValue(String field)
187   {
188     String returnField = null;
189     if (field!=null)
190     {
191       if (field.equals("date_formatted") || field.equals("webdb_create_short") )
192       {
193                   if (hasValueForField("date"))
194         returnField = StringUtil.webdbDate2readableDate(getValue("webdb_create"));
195                 }
196       else if (field.equals("description_parsed"))
197         returnField = getDescriptionParsed();
198       else if (field.equals("description_sentence"))
199         returnField = getDescriptionSentence();
200       else if (field.equals("content_data_parsed"))
201         returnField = getContentDataParsed();
202       else
203         return super.getValue(field);
204     }
205     return returnField;
206         }
207
208   public TemplateModel get(java.lang.String key) throws TemplateModelException
209   {
210     if (key!=null) {
211       if (_entCache.containsKey(key)) {
212         return (TemplateModel)_entCache.get(key);
213       }
214       if (key.equals("to_comments")) {
215         try {
216           _entCache.put(key, getComments());
217           return (TemplateModel)_entCache.get(key);
218         } catch (Exception ex) {
219           theLog.printWarning("-- getComments: could not fetch data " + ex.toString());
220           throw new TemplateModelException(ex.toString());
221         }
222       }
223       if (key.equals("to_media_images")) {
224         try {
225           _entCache.put(key, getImagesForContent());
226           return (TemplateModel)_entCache.get(key);
227         }
228         catch (Exception ex) {
229           theLog.printWarning("-- getImagesForContent: could not fetch data " + ex.toString());
230           throw new TemplateModelException(ex.toString());
231         }
232       }
233       if (key.equals("to_media_audio")) {
234         try {
235           _entCache.put(key, getAudioForContent());
236           return (TemplateModel)_entCache.get(key);
237         }
238         catch (Exception ex) {
239           theLog.printWarning("-- getAudioForContent: could not fetch data " + ex.toString());
240           throw new TemplateModelException(ex.toString());
241         }
242       }
243       if (key.equals("to_media_video")) {
244         try {
245           _entCache.put(key, getVideoForContent());
246           return (TemplateModel)_entCache.get(key);
247         }
248         catch (Exception ex) {
249           theLog.printWarning("-- getVideoForContent: could not fetch data " + ex.toString());
250           throw new TemplateModelException(ex.toString());
251         }
252       }
253       if (key.equals("to_media_other")) {
254         try {
255           _entCache.put(key, getOtherMediaForContent());
256           return (TemplateModel)_entCache.get(key);
257         }
258         catch (Exception ex) {
259           theLog.printWarning("-- getOtherMediaForContent: could not fetch data " + ex.toString());
260           throw new TemplateModelException(ex.toString());
261         }
262       }
263       else if (key.equals("to_media_icon")) {
264         try {
265           _entCache.put(key, getUploadedMediaForNewswire());
266           return (TemplateModel)_entCache.get(key);
267         }
268         catch (Exception ex) {
269           theLog.printWarning("-- getUploadedMediaForNewswire: could not fetch data " + ex.toString());
270           throw new TemplateModelException(ex.toString());
271         }
272       }
273       else if (key.equals("to_topics")) {
274         try {
275           _entCache.put(key, 
276                         DatabaseContentToTopics.getInstance().getTopics(this));
277           return (TemplateModel)_entCache.get(key);
278         }
279         catch (Exception ex) {
280           theLog.printWarning("-- getTopics: could not fetch data " + ex.toString());
281           throw new TemplateModelException(ex.toString());
282         }
283       }
284       else {
285         return new SimpleScalar(getValue(key));
286       }
287
288     }
289     return null;
290   }
291
292
293
294
295         /**
296          * overridden method setValues to patch creator_main_url
297          */
298         public void setValues(HashMap theStringValues) {
299                 if (theStringValues != null) {
300                         if (theStringValues.containsKey("creator_main_url")){
301                                 if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){
302                                         theStringValues.remove("creator_main_url");
303         } else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){
304           theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url")));
305         }
306       }
307                 }
308                 super.setValues(theStringValues);
309         }
310
311
312   private String getContentDataParsed() {
313     String returnField = getValue("content_data");
314     if ((returnField!=null) && (returnField.length()>0) ) {
315       returnField=StringUtil.deleteForbiddenTags(returnField);
316       //create http-links and email-links
317       if (getValue("is_html").equals("0")) {
318         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
319                                             mirconf_mailLinkName,mirconf_extLinkName,
320                                             mirconf_intLinkName);
321       }
322       // commented this out as I don't think it necessary as we don't
323       // "encodeHTML" in the first place anymore.. -mh 2002.07.19
324       //returnField = StringUtil.decodeHTMLinTags(returnField);
325     }
326     return returnField;
327   }
328
329   private String getDescriptionSentence() {
330     String returnField = getValue("description");
331     if (returnField != null && returnField.length()>0) {
332        returnField = StringUtil.removeHTMLTags(returnField);
333        int endOfFirstSentence=StringUtil.findEndOfSentence(returnField,0);
334        if (endOfFirstSentence > 0){
335          returnField = returnField.substring(0,endOfFirstSentence);
336        }
337     }
338     return returnField;
339   }
340
341   private String getDescriptionParsed() {
342     String returnField = getValue("description");
343     if (returnField != null && returnField.length()>0) {
344       returnField = StringUtil.deleteForbiddenTags(returnField);
345       if (getValue("is_html").equals("0")) {
346         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
347                                             mirconf_mailLinkName,mirconf_extLinkName,
348                                             mirconf_intLinkName);
349       }
350       returnField = StringUtil.decodeHTMLinTags(returnField);
351     }
352     return returnField;
353   }
354
355         /**
356          * fetches all the comments belonging to an article
357          *
358          * @return freemarker.template.SimpleList
359          */
360         private EntityList getComments() throws StorageObjectException {
361                 return ((DatabaseContent)theStorageObject).getComments(this);
362         }
363
364   // @todo this needs to optimized. expensive SQL
365   private SimpleHash getUploadedMediaForNewswire()
366     throws StorageObjectException, TemplateModelException
367   {
368     // fetching/setting the images
369     // return to_media_icons
370     String        tinyIcon = null, iconAlt = null;
371     MirMedia      mediaHandler = null;
372     EntityUploadedMedia uploadedMedia;
373     Entity        mediaType;
374     SimpleHash    returnHash = new SimpleHash();
375
376     EntityList upMediaEntityList =
377                     DatabaseContentToMedia.getInstance().getUploadedMedia(this);
378     if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
379
380       for (int n=0; n < upMediaEntityList.size();n++) {
381         uploadedMedia = (EntityUploadedMedia)upMediaEntityList.elementAt(n);
382         mediaType = uploadedMedia.getMediaType();
383         try {
384           mediaHandler = MediaHelper.getHandler( mediaType );
385         } catch (MirMediaException ex) {
386           throw new TemplateModelException(ex.toString());
387         }
388         //the "best" media type to show
389         if (mediaHandler.isVideo()) {
390           tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
391           iconAlt = "Video";
392           break;
393         } else if (mediaHandler.isAudio()) {
394           tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
395           iconAlt = "Audio";
396         } else if (tinyIcon == null && !mediaHandler.isImage()) {
397           tinyIcon = mediaHandler.getTinyIcon();
398           iconAlt = mediaHandler.getIconAlt();
399         }
400
401       }
402       //it only has image(s)
403       if (tinyIcon == null) {
404         tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
405         iconAlt = "Image";
406       }
407     // uploadedMedia Entity list is empty.
408     // we only have text
409     } else {
410       tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
411       iconAlt = "Text";
412     }
413     returnHash.put("tiny_icon", mirconf_imageRoot+"/"+tinyIcon);
414     returnHash.put("icon_alt", iconAlt);
415     return returnHash;
416   }
417
418   private boolean hasMedia() throws StorageObjectException
419   {
420     if (_hasMedia == null) {
421       _hasMedia =
422         new Boolean(DatabaseContentToMedia.getInstance().hasMedia(this));
423     }
424     return _hasMedia.booleanValue();
425   }
426
427   //######## @todo all of the following getBlahForContent should have
428   // and optimized version where LIMIT=1 sql for list view.
429   private EntityList getImagesForContent()
430     throws StorageObjectException, TemplateModelException
431   {
432     if (hasMedia())
433       return DatabaseContentToMedia.getInstance().getImages(this);
434     else
435       return null;
436   }
437
438   private EntityList getAudioForContent()
439     throws StorageObjectException, TemplateModelException
440   {
441     if (hasMedia())
442       return DatabaseContentToMedia.getInstance().getAudio(this) ;
443     else
444       return null;
445   }
446
447   private EntityList getVideoForContent()
448     throws StorageObjectException, TemplateModelException
449   {
450     if (hasMedia())
451       return DatabaseContentToMedia.getInstance().getVideo(this) ;
452     else
453       return null;
454   }
455
456   private EntityList getOtherMediaForContent()
457     throws StorageObjectException, TemplateModelException
458   {
459     if (hasMedia())
460       return DatabaseContentToMedia.getInstance().getOther(this);
461     else
462       return null;
463   }
464
465 }