KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > shared > BigText_Field


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 //
14
// BigText_Field
15
// EV 14.01.20001
16
//
17
// handleField( mode, jParams )
18
//
19

20 package org.jahia.engines.shared;
21
22 import java.net.MalformedURLException JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Date JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.HashSet JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.Set JavaDoc;
29 import java.util.Vector JavaDoc;
30
31 import org.apache.log4j.Logger;
32 import org.jahia.content.ContentFieldKey;
33 import org.jahia.content.ContentPageKey;
34 import org.jahia.content.ObjectLink;
35 import org.jahia.data.containers.JahiaContainer;
36 import org.jahia.data.fields.JahiaField;
37 import org.jahia.data.fields.JahiaFieldDefinitionProperties;
38 import org.jahia.engines.EngineMessages;
39 import org.jahia.engines.JahiaEngine;
40 import org.jahia.engines.JahiaEngineTools;
41 import org.jahia.exceptions.JahiaException;
42 import org.jahia.params.ParamBean;
43 import org.jahia.registries.ServicesRegistry;
44 import org.jahia.services.acl.JahiaBaseACL;
45 import org.jahia.services.htmlparser.ActiveXServerURLCleanupDOMVisitor;
46 import org.jahia.services.htmlparser.ExtractLinksDOMVisitor;
47 import org.jahia.services.htmlparser.JahiaTextContentTidy;
48 import org.jahia.services.pages.ContentPage;
49 import org.jahia.services.sites.JahiaSite;
50 import org.jahia.urls.ContentServletURL;
51 import org.jahia.utils.I18n;
52 import org.jahia.utils.JahiaString;
53 import org.jahia.utils.JahiaTools;
54
55 public class BigText_Field
56 {
57
58     private static Logger logger = Logger.getLogger(BigText_Field.class);
59
60     private static BigText_Field theObject = null;
61     private static final String JavaDoc JSP_FILE = "/jsp/jahia/engines/shared/bigtext_field.jsp";
62
63     public static final String JavaDoc HTMLEDITOR_VIEW_HELPER_ATTRIBUTE =
64             "org.jahia.engines.shared.BigText_Field.HTMLEditorsViewHelper";
65
66     /***
67         * getInstance
68         * AK 19.12.2000
69         *
70         */

71     public static synchronized BigText_Field getInstance()
72     {
73         if (theObject == null) {
74             theObject = new BigText_Field();
75         }
76         return theObject;
77     } // end getInstance
78

79
80
81     /***
82         * handles the field actions
83         *
84         * @param jParams a ParamBean object
85         * @param mode the mode, according to JahiaEngine
86         * @return true if everything went okay, false if not
87         * @see org.jahia.engines.JahiaEngine
88         *
89         */

90     public boolean handleField( ParamBean jParams, Integer JavaDoc modeInt, HashMap JavaDoc engineMap )
91     throws JahiaException
92     {
93         int mode = modeInt.intValue();
94         JahiaField theField = (JahiaField) engineMap.get( "theField" );
95         initHtmlEditorsHelpers(engineMap,jParams);
96
97         logger.debug("handling mode : " + mode + " for field " + theField.getID() + " value=" + theField.getValue());
98
99         switch (mode)
100         {
101             case (JahiaEngine.LOAD_MODE) : return composeEngineMap( jParams, engineMap, theField );
102             case (JahiaEngine.UPDATE_MODE) : return getFormData( jParams, engineMap, theField );
103             case (JahiaEngine.SAVE_MODE) : return saveData( jParams, engineMap, theField );
104         }
105         return false;
106     } // end handleField
107

108
109
110     /***
111         * gets POST data from the form and saves it in session
112         *
113         * @param jParams a ParamBean object
114         * @param engineMap the engine hashmap
115         * @param theField the field we are working on
116         * @return true if everything went okay, false if not
117         *
118         */

119     private boolean getFormData( ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField )
120     throws JahiaException
121     {
122         boolean out = true;
123
124         // field value was changed? no --> do not need to process it
125
String JavaDoc fieldValueChanged = jParams.getRequest().getParameter(
126           "_" + theField.getID() + "_isDirty");
127         if (fieldValueChanged != null && "false".equals(fieldValueChanged))
128           return true;
129
130         /*
131         String sConnectType = jParams.getRequest().getParameter("connectType");
132         int connectType = sConnectType != null ? Integer.parseInt(sConnectType)
133                                               : theField.getConnectType();
134         */

135
136         String JavaDoc fieldValue = jParams.getRequest().getParameter( "_" + theField.getID());
137
138         if (fieldValue != null) {
139
140             fieldValue = JahiaTools.replacePattern(fieldValue,"|","|");
141             if ("ISO-8859-1".equalsIgnoreCase(jParams.settings().
142                                               getDefaultResponseBodyEncoding())) {
143                 // This code is used to transform submissions that might contain
144
// Windows 1252 characters (happens mostly when copy-pasting
145
// from Word documents) to ISO-8859-1 equivalents. Note that
146
// some of these conversions are actually LONGER than the
147
// original. For example the Euro character gets changed to
148
// "Euro" string. This conversion is not necessary for UTF-8
149
// because copy-paste does the conversion automatically in that
150
// case.
151
fieldValue = I18n.windows1252ToISO(fieldValue);
152             }
153             String JavaDoc oriFieldValue = fieldValue;
154
155             JahiaSite site = ServicesRegistry.getInstance().getJahiaSitesService()
156                            .getSite(theField.getJahiaID());
157
158             if ( site.getHtmlCleanup()==1 ){
159                 Vector JavaDoc DOMVisitors = ServicesRegistry.getInstance()
160                                      .getHtmlParserService()
161                                      .getHtmlDOMVisitors(theField.getJahiaID());
162
163
164                 ExtractLinksDOMVisitor linkExtractionVisitor = null;
165                 if (site.getHtmlMarkupFiltering() == 1) {
166                     linkExtractionVisitor = new ExtractLinksDOMVisitor();
167                     linkExtractionVisitor.init(site.getID());
168                     DOMVisitors.add(linkExtractionVisitor);
169                 }
170
171                 String JavaDoc serverURL = jParams.getRequest().getParameter("serverURL");
172
173                 if ( serverURL != null ){
174                     ActiveXServerURLCleanupDOMVisitor rsnfURLVisitor =
175                         new ActiveXServerURLCleanupDOMVisitor(serverURL);
176                     DOMVisitors.add(rsnfURLVisitor);
177                 }
178
179                 fieldValue = JahiaTextContentTidy.tidyPreProcessing(fieldValue);
180                 fieldValue = ServicesRegistry.getInstance().getHtmlParserService()
181                        .parse(fieldValue,DOMVisitors,theField.getSiteID());
182                 fieldValue = JahiaTextContentTidy.tidyPostProcessing(fieldValue);
183
184                 if (linkExtractionVisitor != null) {
185                     findAndStoreCrossLinks(linkExtractionVisitor, jParams, engineMap);
186                 }
187             }
188
189             EngineMessages resultMessages = ServicesRegistry.getInstance().getHtmlParserService()
190                 .checkTextParsingErrors(fieldValue);
191             if ( !resultMessages.isEmpty() ){
192                 resultMessages.saveMessages(String.valueOf(theField.getID()) + ".", jParams.getRequest());
193                 fieldValue = oriFieldValue;
194                 out = false;
195             }
196
197             if (!fieldValue.toLowerCase().startsWith("<html>")) {
198                 fieldValue = "<html>" + fieldValue + "</html>";
199             }
200
201         } else {
202             fieldValue = theField.getValue();
203         }
204         fieldValue = JahiaString.getProperStr(fieldValue, jParams.getLocale());
205         theField.setValue( fieldValue );
206         theField.setObject(null);
207
208         return out;
209     } // end getFormData
210

211     private void findAndStoreCrossLinks (ExtractLinksDOMVisitor
212                                          linkExtractionVisitor, ParamBean paramBean, HashMap JavaDoc engineMap) {
213         Set JavaDoc pageXRefs = new HashSet JavaDoc();
214         Iterator JavaDoc linkIter = linkExtractionVisitor.getDocumentLinks().iterator();
215         while (linkIter.hasNext()) {
216             String JavaDoc curLink = (String JavaDoc) linkIter.next();
217             if (curLink == null || curLink.length() == 0)
218               continue;
219             logger.debug("Found link [" + curLink + "] in bigtext field.");
220
221             // first we must find the original URL if this was a rewritten URL
222
String JavaDoc originalURL = ServicesRegistry.getInstance().getURLRewritingService().getOriginalFromRewritten(curLink);
223             if (originalURL == null) {
224                 originalURL = curLink;
225             }
226             // we now need to determine if this URL concerns this
227
// Jahia installation or if it is an external Jahia
228
// URL or even a non-Jahia URL. First we check if the
229
// URL contains a Jahia servlet path that corresponds
230
// to this Jahia. Then we have the following
231
// possibilities :
232
// - the URL contains a localhost hostname, in which
233
// case we assume it is a Jahia which seems reasonable
234
// - the URL contains a domain name that is contained
235
// in this Jahia's site database
236
// - the URL contains a /site/* parameter that contains
237
// a site key that is in our local Jahia database.
238
// Note that none of these can FULLY guarantee that we
239
// have recognized a local Jahia URL, but they make a
240
// best effort.
241
try {
242                 if (ContentServletURL.isContentServletURL(paramBean.getRequest(), originalURL, true)) {
243                     // ok we have found what looks like a Jahia content URL, we
244
// must now check if it is indeed a local Jahia URL before
245
// seeing to what content object is it referring.
246
ContentServletURL contentServletURL = new ContentServletURL(paramBean.getRequest(), originalURL, true);
247                     String JavaDoc siteKey = contentServletURL.getPathInfoParameter("site");
248                     String JavaDoc pageIDStr = contentServletURL.getPathInfoParameter("pid");
249                     String JavaDoc hostName = contentServletURL.getHostName();
250                     if (logger.isDebugEnabled())
251                       logger.debug("Found Jahia URL : site=[" +
252                                  siteKey +
253                                  "] pid=[" +
254                                   pageIDStr +
255                                  "] hostName=[" +
256                                   hostName + "]");
257                      JahiaSite site = null;
258                      try {
259                          if ( (siteKey != null) && (!"".equals(siteKey))) {
260                              site = ServicesRegistry.getInstance().
261                                  getJahiaSitesService().getSiteByKey(siteKey);
262                          } else if ( (hostName != null) && (!"".equals(hostName))) {
263                              site = ServicesRegistry.getInstance().
264                                  getJahiaSitesService().getSiteByServerName(
265                                  hostName);
266                          }
267                          if (site == null) {
268                              site = ParamBean.getDefaultSite();
269                          }
270                          if (pageIDStr != null) {
271                              // this looks a LOT like a Jahia page ID.
272
int pageID = Integer.parseInt(pageIDStr);
273                              try {
274                                  ContentPage contentPage = ContentPage.getPage(
275                                      pageID);
276                                  if (contentPage != null) {
277                                      // we found a page that corresponds to this
278
// field !
279
pageXRefs.add(new Integer JavaDoc(pageID));
280                                  }
281                              } catch (JahiaException ex) {
282                                  logger.debug("Page " + pageID +
283                                      "not found, ignoring in references");
284                              }
285                          }
286                      } catch (JahiaException je) {
287                          logger.warn(
288                              "Exception raised while trying to find site from URL : " +
289                              contentServletURL +
290                              ", we will ignore this URL instead of processing it.",
291                              je);
292                      } catch (NumberFormatException JavaDoc nfe) {
293                          logger.warn("Invalid page number " + pageIDStr + ", ignoring URL " + contentServletURL, nfe);
294                      }
295                 }
296             } catch (MalformedURLException JavaDoc mue) {
297                 logger.warn("Error in parsed URL, ignoring", mue);
298             }
299         }
300         engineMap.put("pageXRefs", pageXRefs);
301     }
302
303
304
305     /***
306         * saves data in datasource
307         *
308         * @param jParams a ParamBean object
309         * @param engineMap the engine hashmap
310         * @param theField the field we are working on
311         * @return true if everything went okay, false if not
312         *
313         */

314     private boolean saveData( ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField )
315     throws JahiaException
316     {
317
318         // 0 for parentAclID in saveField, because field already exists
319
// -> field already has an aclID
320
// -> no need to create a new one
321
Set JavaDoc pageXRefs = (Set JavaDoc) engineMap.get("pageXRefs");
322         if ((pageXRefs != null) && (pageXRefs.size() > 0)) {
323
324             ContentFieldKey fieldKey = new ContentFieldKey(theField.getID());
325
326             // first we remove all the existing references for this object.
327
ArrayList JavaDoc references = ObjectLink.findByTypeAndLeftObjectKey("hardcodedLink", fieldKey);
328             Iterator JavaDoc refIterator = references.iterator();
329             while (refIterator.hasNext()) {
330                 ObjectLink curLink = (ObjectLink) refIterator.next();
331                 curLink.remove();
332             }
333
334             Iterator JavaDoc pageXRefIter = pageXRefs.iterator();
335             while (pageXRefIter.hasNext()) {
336                 Integer JavaDoc curPageIDInt = (Integer JavaDoc) pageXRefIter.next();
337                 logger.debug("Found reference to page " + curPageIDInt + " in this bigtext");
338                 ObjectLink.createLink(fieldKey,
339                     new ContentPageKey(curPageIDInt.intValue()), "hardcodedLink", 1,
340                     new Date JavaDoc(),
341                     "root:0", new Date JavaDoc(), "root:0", new HashMap JavaDoc(),
342                     new HashMap JavaDoc(), new HashMap JavaDoc());
343             }
344         }
345
346         return theField.save(jParams);
347
348     } // end saveData
349

350
351
352     /***
353         * composes engine hash map
354         *
355         * @param jParams a ParamBean object
356         * @param engineMap the engine hashmap
357         * @param theField the field we are working on
358         * @return true if everything went okay, false if not
359         *
360         */

361     private boolean composeEngineMap( ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField )
362     throws JahiaException
363     {
364
365         boolean editable = false;
366         JahiaContainer theContainer = (JahiaContainer)engineMap.get("theContainer");
367         if ( theContainer == null ){
368             // in case of a field , not a field in a container
369
editable = true;
370         } else {
371             HashMap JavaDoc ctnListFieldAcls = (HashMap JavaDoc) engineMap
372                     .get("ctnListFieldAcls");
373
374             if (theContainer.getListID() != 0 && ctnListFieldAcls != null
375                     && ctnListFieldAcls.size() > 0) {
376                 JahiaBaseACL acl = JahiaEngineTools.getCtnListFieldACL(
377                         ctnListFieldAcls, theField.getID());
378                 if (acl != null) {
379                     editable = acl.getPermission(jParams.getUser(),
380                             JahiaBaseACL.WRITE_RIGHTS, true);
381                 }
382             } else {
383                 editable = true;
384             }
385         }
386
387         String JavaDoc output = "";
388         String JavaDoc forward = theField.getDefinition()
389             .getProperty(JahiaFieldDefinitionProperties.FIELD_UPDATE_JSP_FILE_PROP);
390         if ( forward == null ){
391           forward = JSP_FILE;
392           if ( !editable ){
393             forward = JahiaEngine.NOT_EDITABLE_FIELD;
394           }
395         }
396         
397         initHtmlEditorsHelpers(engineMap,jParams);
398
399         if ( editable ){
400             String JavaDoc fieldValue = theField.getValue();
401             if ( fieldValue == null ){
402                 fieldValue = "";
403             }
404
405             // SCSE: what for do we need this stuff here?
406
// these tasks must be performed on update and not here
407
//
408
// String oriFieldValue = fieldValue;
409
// JahiaSite site = ServicesRegistry.getInstance().getJahiaSitesService()
410
// .getSite(theField.getJahiaID());
411
//
412
// if ( site.getHtmlCleanup()==1 ){
413
// Vector DOMVisitors = ServicesRegistry.getInstance()
414
// .getHtmlParserService()
415
// .getHtmlDOMVisitors(theField.getJahiaID());
416
//
417
// fieldValue = JahiaTextContentTidy.tidyPreProcessing(fieldValue);
418
// fieldValue = ServicesRegistry.getInstance().getHtmlParserService()
419
// .parse(fieldValue,DOMVisitors,theField.getSiteID());
420
// fieldValue = JahiaTextContentTidy.tidyPostProcessing(fieldValue);
421
// }
422
//
423
// EngineMessages resultMessages = ServicesRegistry.getInstance().getHtmlParserService()
424
// .checkTextParsingErrors(fieldValue);
425
// if ( !resultMessages.isEmpty() ){
426
// resultMessages.saveMessages(String.valueOf(theField.getID()) + ".", jParams.getRequest());
427
// fieldValue = oriFieldValue;
428
// }
429

430             // FIXME ENCODING
431
// we can't do such encoding here since it depend of the Editor ( Simple editor
432
// act differently from ActiveX editor...)
433
//theField.setValue( FormDataManager.getInstance().formEncode( fieldValue ) );
434

435             theField.setValue(fieldValue);
436             output = ServicesRegistry.getInstance().getJahiaFetcherService().fetchServlet( jParams, forward );
437         } else {
438             output = ServicesRegistry.getInstance().getJahiaFetcherService().fetchServlet( jParams, forward );
439         }
440         engineMap.put( "fieldForm", output );
441
442         return true;
443     } // end composeEngineMap
444

445
446     private void initHtmlEditorsHelpers(HashMap JavaDoc engineMap, ParamBean jParams)
447     throws JahiaException {
448
449         HtmlEditorsViewHelper heViewHelper = (HtmlEditorsViewHelper)
450         engineMap.get(BigText_Field.HTMLEDITOR_VIEW_HELPER_ATTRIBUTE);
451         if ( heViewHelper == null ){
452             heViewHelper = new HtmlEditorsViewHelper();
453             heViewHelper.loadHtmlEditors(jParams.getSiteID(),jParams.getRequest());
454             engineMap.put(BigText_Field.HTMLEDITOR_VIEW_HELPER_ATTRIBUTE,
455                           heViewHelper);
456         }
457         // define a default Html Editor
458
String JavaDoc selectedHtmlEditor =
459                 jParams.getRequest().getParameter("htmlEditor");
460         if ( selectedHtmlEditor != null ){
461             heViewHelper.setDefaultEditorID(selectedHtmlEditor);
462         }
463
464         // define a default CSS
465
String JavaDoc selectedCSS =
466                 jParams.getRequest().getParameter("htmlEditorCSS");
467         if ( selectedCSS != null ){
468             heViewHelper.setDefaultCSSID(selectedCSS);
469         }
470
471     }
472
473
474 } // end BigText_Field
475
Popular Tags