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