28707fe3d05fa5a7d47ce823e6703c1038f63eb0
[mir.git] / source / mircoders / entity / EntityContent.java
1 package mircoders.entity;
2
3 import java.lang.*;
4 import java.io.*;
5 import java.util.*;
6 import java.sql.*;
7 import java.lang.reflect.*;
8
9 import freemarker.template.*;
10
11 import mir.entity.*;
12 import mir.misc.*;
13 import mir.media.*;
14 import mir.storage.*;
15
16 import mircoders.storage.*;
17
18 /**
19  * this class implements mapping of one line of the database table content
20  * to a java object
21  *
22  * @author RK
23  * @version 2001
24  */
25
26
27 public class EntityContent extends Entity
28 {
29
30   String mirconf_extLinkName  = MirConfig.getProp("Producer.ExtLinkName");
31   String mirconf_intLinkName  = MirConfig.getProp("Producer.IntLinkName");
32   String mirconf_mailLinkName = MirConfig.getProp("Producer.MailLinkName");
33   String mirconf_imageRoot    = MirConfig.getProp("Producer.ImageRoot");
34
35         // constructors
36
37         public EntityContent()
38         {
39                 super();
40     //content_data is now filed-type "text"
41                 //streamedInput = new ArrayList();
42                 //streamedInput.add("content_data");
43         }
44
45         public EntityContent(StorageObject theStorage) {
46                 this();
47                 setStorage(theStorage);
48         }
49
50         //
51         // methods
52
53  /**
54         * set is_produced flag for the article
55         */
56
57         public void setProduced(boolean yesno) throws StorageObjectException
58         {
59                 Connection con=null;Statement stmt=null;
60                 String value = (yesno) ? "1":"0";
61                 String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
62                 try {
63                         con = theStorageObject.getPooledCon();
64                         /** @todo should be preparedStatement: faster!! */
65                         stmt = con.createStatement();
66                         theStorageObject.executeUpdate(stmt,sql);
67                 } catch (StorageObjectException e) {
68             throwStorageObjectException(e, "\n -- set produced failed");
69                 } catch (SQLException e) {
70             throwStorageObjectException(e, "\n -- set produced failed");
71                 } finally {
72                         theStorageObject.freeConnection(con,stmt);
73                 }
74         }
75
76
77  /**
78         * make openposting to newswire
79         */
80
81         public void newswire() throws StorageObjectException
82         {
83                 String sql = "update content set to_article_type='1', is_produced='0' where id='" + getId()+"'";
84                 try {
85                                 theStorageObject.executeUpdate(sql);
86                 } catch (StorageObjectException e) {
87             throwStorageObjectException(e, "\n -- newswire failed");
88                 } catch (SQLException e) {
89             throwStorageObjectException(e, "\n -- newswire failed");
90                 }
91         }
92
93
94  /**
95         * dettach from media
96         */
97         public void dettach(String cid,String mid) throws StorageObjectException
98         {
99                 if (mid!=null){
100                         try{
101                                 DatabaseContentToMedia.getInstance().delete(cid,mid);
102                         } catch (Exception e){
103                 throwStorageObjectException(e, "\n -- failed to get instance");
104                         }
105                         //set Content to unproduced
106                         setProduced(false);
107                 }
108         }
109
110  /**
111         * attach to media
112         */
113
114         public void attach(String mid) throws StorageObjectException
115         {
116                 if (mid!=null) {
117                         //write media-id mid and content-id in table content_x_media
118                         try{
119                                 DatabaseContentToMedia.getInstance().addMedia(getId(),mid);
120                         } catch(StorageObjectException e){
121                                 throwStorageObjectException(e, "attach: could not get the instance");
122                         }
123                         //set Content to unproduced
124                         setProduced(false);
125                 }       else {
126                         theLog.printError("EntityContent: attach without mid");
127                 }
128         }
129
130         /**
131          * overridden method getValue to include formatted date into every
132          * entityContent
133          */
134
135         public String getValue(String field)
136   {
137     String returnField = null;
138     if (field!=null)
139     {
140       if (field.equals("date_formatted"))
141       {
142                   if (hasValueForField("date"))
143         returnField = StringUtil.webdbDate2readableDate(getValue("date"));
144                 }
145       else if (field.equals("description_parsed"))
146         returnField = getDescriptionParsed();
147       else if (field.equals("content_data_parsed"))
148         returnField = getContentDataParsed();
149       else
150         return super.getValue(field);
151     }
152     return returnField;
153         }
154
155   public TemplateModel get(java.lang.String key) throws TemplateModelException
156   {
157     if (key!=null) {
158       if (key.equals("to_comments")) {
159         try {
160           return getComments();
161         }
162         catch (Exception ex) {
163           theLog.printWarning("-- getComments: could not fetch data " + ex.toString());
164           throw new TemplateModelException(ex.toString());
165         }
166       }
167       if (key.equals("to_media_content")) {
168         try {
169           /** @todo why this loggin to System.err and not
170            *  theLog.printDebugInfo() ? / rk */
171           System.err.println("ASKED FOR MEDIA");
172           SimpleList t = getUploadedMediaForContent();
173           //SimpleHash o = t.next();
174
175           if (t == null) {
176             System.err.println("NULL -- LIST "+this.getId());
177           } else {
178             SimpleHash o = (SimpleHash)t.next();
179             System.err.println("SCALAR: "+o.get("url"));
180           }
181
182           t.rewind();
183           //return getUploadedMediaForContent();
184           return t;
185         }
186         catch (Exception ex) {
187           System.err.println("ASKED EXCE");
188           theLog.printWarning("-- getUploadedMediaForContent: could not fetch data " + ex.toString());
189           throw new TemplateModelException(ex.toString());
190         }
191       }
192       else if (key.equals("to_media_icon")) {
193         try {
194           return getUploadedMediaForNewswire();
195         }
196         catch (Exception ex) {
197           theLog.printWarning("-- getUploadedMediaForNewswire: could not fetch data " + ex.toString());
198           throw new TemplateModelException(ex.toString());
199         }
200       }
201       else if (key.equals("to_media_list")) {
202         try {
203           return getUploadedMediaForList();
204         }
205         catch (Exception ex) {
206           theLog.printWarning("-- getUploadedMediaForList: could not fetch data " + ex.toString());
207           throw new TemplateModelException(ex.toString());
208         }
209       }
210       else if (key.equals("to_topics")) {
211         try {
212           HTMLTemplateProcessor.makeSimpleList(DatabaseContentToTopics.getInstance().getTopics(this));
213         }
214         catch (Exception ex) {
215           theLog.printWarning("-- getTopics: could not fetch data " + ex.toString());
216           throw new TemplateModelException(ex.toString());
217         }
218       }
219       else {
220         return new SimpleScalar(getValue(key));
221       }
222
223     }
224     return null;
225   }
226
227
228
229
230         /**
231          * overridden method setValues to patch creator_main_url
232          */
233         public void setValues(HashMap theStringValues) {
234                 if (theStringValues != null) {
235                         if (theStringValues.containsKey("creator_main_url")){
236                                 if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){
237                                         theStringValues.remove("creator_main_url");
238         } else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){
239           theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url")));
240         }
241       }
242                 }
243                 super.setValues(theStringValues);
244         }
245
246
247   private String getContentDataParsed() {
248     String returnField = getValue("content_data");
249     if (returnField!=null & returnField.length()>0 ) {
250       returnField=StringUtil.deleteForbiddenTags(returnField);
251       //create http-links and email-links
252       if (getValue("is_html").equals("0")) {
253         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
254                                             mirconf_mailLinkName,mirconf_extLinkName,
255                                             mirconf_intLinkName);
256       }
257       returnField = StringUtil.decodeHTMLinTags(returnField);
258     }
259     return returnField;
260   }
261
262
263   private String getDescriptionParsed() {
264     String returnField = getValue("description");
265     if (returnField != null && returnField.length()>0) {
266       returnField = StringUtil.deleteForbiddenTags(returnField);
267       if (getValue("is_html").equals("0")) {
268         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
269                                             mirconf_mailLinkName,mirconf_extLinkName,
270                                             mirconf_intLinkName);
271       }
272       returnField = StringUtil.decodeHTMLinTags(returnField);
273     }
274     return returnField;
275   }
276
277         /**
278          * fetches all the comments belonging to an article
279          *
280          * @return freemarker.template.SimpleList
281          */
282         private SimpleList getComments() throws StorageObjectException {
283                 return ((DatabaseContent)theStorageObject).getComments(this);
284         }
285
286   private SimpleHash getUploadedMediaForNewswire()
287     throws StorageObjectException, TemplateModelException
288   {
289     // fetching/setting the images
290     // return to_media_icons
291     String        tinyIcon = null, iconAlt = null;
292     MirMedia      mediaHandler = null;
293     Database      mediaStorage;
294     EntityMedia   uploadedMedia;
295     Entity        mediaType;
296     SimpleHash    returnHash = new SimpleHash();
297
298     EntityList upMediaEntityList =
299                     DatabaseContentToMedia.getInstance().getUploadedMedia(this);
300     if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
301
302       for (int n=0; n < upMediaEntityList.size();n++) {
303         uploadedMedia = (EntityMedia)upMediaEntityList.elementAt(n);
304         mediaType = uploadedMedia.getMediaType();
305         try {
306           // ############### TODO: merge these and the getURL call into one
307           // getURL helper call that just takes the Entity as a parameter
308           // along with media_type
309           mediaHandler = MediaHelper.getHandler( mediaType );
310           mediaStorage = MediaHelper.getStorage( mediaType,
311                                                 "mircoders.storage.Database");
312         } catch (MirMediaException ex) {
313           throw new TemplateModelException(ex.toString());
314         }
315         //the "best" media type to show
316         if (mediaHandler.isVideo()) {
317           tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
318           iconAlt = "Video";
319           break;
320         } else if (mediaHandler.isAudio()) {
321           tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
322           iconAlt = "Audio";
323         } else if (tinyIcon == null && !mediaHandler.isImage()) {
324           tinyIcon = mediaHandler.getTinyIcon();
325           iconAlt = mediaHandler.getIconAlt();
326         }
327       }
328       //it only has image(s)
329       if (tinyIcon == null) {
330         tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
331         iconAlt = "Image";
332       }
333
334     // uploadedMedia Entity list is empty.
335     // we only have text
336     } else {
337       tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
338       iconAlt = "Text";
339     }
340
341     returnHash.put("tiny_icon", mirconf_imageRoot+"/"+tinyIcon);
342     returnHash.put("icon_alt", iconAlt);
343     return returnHash;
344   }
345
346   private SimpleHash getUploadedMediaForList()
347     throws StorageObjectException, TemplateModelException
348   {
349     SimpleHash returnHash = new SimpleHash();
350     //media to content
351     EntityList currentMediaList = DatabaseContentToMedia.getInstance().getUploadedMedia(this);
352     if (currentMediaList!=null && currentMediaList.getCount()>=1) {
353       SimpleList          mediaListAudio = new SimpleList();
354       SimpleList          mediaListImages = new SimpleList();
355       SimpleList          mediaListVideo = new SimpleList();
356       SimpleList          mediaListOther = new SimpleList();
357       Entity              upMedia;
358       Entity              mediaType;
359       SimpleHash          upMediaSimpleHash;
360       MirMedia            mediaHandler=null;
361       Database            mediaStorage=null;
362
363       for (int n=0; n < currentMediaList.size();n++) {
364         upMedia = currentMediaList.elementAt(n);
365         //upMediaSimpleHash = HTMLTemplateProcessor.makeSimpleHash(upMedia);
366         mediaType = ((EntityMedia)upMedia).getMediaType();
367
368         try {
369           // ############### TODO: merge these and the getURL call into one
370           // getURL helper call that just takes the Entity as a parameter
371           // along with media_type
372           mediaHandler = MediaHelper.getHandler( mediaType );
373           mediaStorage = MediaHelper.getStorage( mediaType,
374                                                 "mircoders.storage.Database");
375         } catch (MirMediaException ex) {
376           throw new TemplateModelException(ex.toString());
377         }
378
379         // ################ TODO: see getUploadedMediaForContent
380         //we most likely need further info
381         upMedia = mediaStorage.selectById(upMedia.getId());
382
383         // putting media in the apropriate list container
384         if (upMedia.getValue("is_published").equals("1")) {
385           if (mediaHandler.isImage()) {
386             //mediaListImages.add(upMediaSimpleHash);
387             mediaListImages.add(upMedia);
388           } else if (mediaHandler.isAudio()) {
389             //mediaListAudio.add(upMediaSimpleHash);
390             mediaListAudio.add(upMedia);
391           } else if (mediaHandler.isVideo()) {
392             //mediaListVideo.add(upMediaSimpleHash);
393             mediaListVideo.add(upMedia);
394           } else {
395             //mediaListOther.add(upMediaSimpleHash);
396             mediaListOther.add(upMedia);
397           }
398         } //end if is_published
399       } //end for
400       returnHash.put("media_audio", mediaListAudio);
401       returnHash.put("media_images", mediaListImages);
402       returnHash.put("media_video", mediaListVideo);
403       returnHash.put("media_other", mediaListOther);
404     } //end if currentMediaList != null
405     return returnHash;
406  }
407
408   private SimpleList getUploadedMediaForContent()
409     throws StorageObjectException, TemplateModelException
410   {
411     /** @todo all logic related to uploaded media should be moved
412      *  to EntityUploadedMedia, selection should just take place
413      *  on published media! .. will fix it later / rk
414      *
415      * ok i moved it... let's see what happens...
416      *
417      *  */
418
419     return HTMLTemplateProcessor.makeSimpleList(
420              DatabaseContentToMedia.getInstance().getUploadedMedia(this) );
421   }
422
423 }