KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > pages > PageProperties_Engine


1 // $Id: PageProperties_Engine.java 15726 2006-11-24 19:05:08Z bpapez $
2
//
3
//
4
// ____.
5
// __/\ ______| |__/\. _______
6
// __ .____| | \ | +----+ \
7
// _______| /--| | | - \ _ | : - \_________
8
// \\______: :---| : : | : | \________>
9
// |__\---\_____________:______: :____|____:_____\
10
// /_____|
11
//
12
// . . . i n j a h i a w e t r u s t . . .
13
//
14

15 //
16
// EV 10.02.20001
17
//
18

19 package org.jahia.engines.pages;
20
21 import java.util.ArrayList JavaDoc;
22 import java.util.Arrays JavaDoc;
23 import java.util.Collections JavaDoc;
24 import java.util.Comparator JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.HashSet JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Locale JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Properties JavaDoc;
32 import java.util.Set JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34 import java.util.Vector JavaDoc;
35 import java.util.regex.Pattern JavaDoc;
36
37 import javax.servlet.http.HttpSession JavaDoc;
38
39 import org.apache.commons.lang.StringUtils;
40 import org.apache.log4j.Logger;
41 import org.jahia.bin.Jahia;
42 import org.jahia.content.ContentObject;
43 import org.jahia.content.ContentPageKey;
44 import org.jahia.data.JahiaData;
45 import org.jahia.data.events.JahiaEvent;
46 import org.jahia.data.fields.JahiaFieldDefinition;
47 import org.jahia.data.fields.JahiaFieldSubDefinition;
48 import org.jahia.engines.EngineMessage;
49 import org.jahia.engines.EngineMessages;
50 import org.jahia.engines.EngineToolBox;
51 import org.jahia.engines.JahiaEngine;
52 import org.jahia.engines.categories.ManageCategories;
53 import org.jahia.engines.lock.LockEngine;
54 import org.jahia.engines.rights.ManageRights;
55 import org.jahia.engines.shared.JahiaPageEngineTempBean;
56 import org.jahia.exceptions.JahiaException;
57 import org.jahia.exceptions.JahiaForbiddenAccessException;
58 import org.jahia.exceptions.JahiaSessionExpirationException;
59 import org.jahia.exceptions.JahiaUpdateLockException;
60 import org.jahia.params.ParamBean;
61 import org.jahia.registries.JahiaFieldDefinitionsRegistry;
62 import org.jahia.registries.ServicesRegistry;
63 import org.jahia.services.audit.LoggingEventListener;
64 import org.jahia.services.cache.Cache;
65 import org.jahia.services.cache.CacheFactory;
66 import org.jahia.services.cache.HtmlCache;
67 import org.jahia.services.fields.ContentPageField;
68 import org.jahia.services.lock.LockKey;
69 import org.jahia.services.lock.LockService;
70 import org.jahia.services.pages.ContentPage;
71 import org.jahia.services.pages.JahiaPage;
72 import org.jahia.services.pages.JahiaPageDefinition;
73 import org.jahia.services.pages.PageProperty;
74 import org.jahia.services.pages.PagePropertyDB;
75 import org.jahia.services.usermanager.JahiaUser;
76 import org.jahia.services.version.EntryLoadRequest;
77 import org.jahia.utils.LanguageCodeConverters;
78 import org.jahia.views.engines.versioning.pages.actions.PagesVersioningAction;
79
80 /**
81  * <p>Title: </p> <p>Description: </p> <p>Copyright: Copyright (c) 2002</p> <p>Company: </p>
82  *
83  * @author Khue Nguyen
84  * @version 1.0
85  */

86 public class PageProperties_Engine implements JahiaEngine {
87
88     /** logging */
89     private static final Logger logger = Logger.getLogger (PageProperties_Engine.class);
90
91     private static final String JavaDoc TEMPLATE_JSP = "page_properties";
92     private static PageProperties_Engine instance = null;
93     public static final String JavaDoc ENGINE_NAME = "pageproperties";
94     private EngineToolBox toolBox;
95
96
97     /**
98      * Default constructor, creates a new <code>PageProperties_Engine</code> instance.
99      */

100     private PageProperties_Engine () {
101         logger.debug (
102                 "***** Starting " + PageProperties_Engine.class.getName () + " engine *****");
103         toolBox = EngineToolBox.getInstance ();
104     }
105
106
107     /**
108      * returns a single instance of the object
109      */

110     public static synchronized PageProperties_Engine getInstance () {
111         if (instance == null) {
112             instance = new PageProperties_Engine ();
113         }
114         return instance;
115     }
116
117     /**
118      * authoriseRender
119      */

120     public boolean authoriseRender (ParamBean jParams) {
121         return toolBox.authoriseRender (jParams);
122     }
123
124     /**
125      * renderLink
126      */

127     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
128             throws JahiaException {
129         String JavaDoc params = EMPTY_STRING;
130 // params += "&mode=display";
131
params += "?mode=display";
132         return jParams.composeEngineUrl (ENGINE_NAME, params);
133     }
134
135     /**
136      * needsJahiaData
137      */

138     public boolean needsJahiaData (ParamBean jParams) {
139         return true;
140     }
141
142     /**
143      * handles the engine actions
144      *
145      * @param jParams a ParamBean object
146      * @param jData a JahiaData object (not mandatory)
147      */

148     public void handleActions (ParamBean jParams, JahiaData jData)
149             throws JahiaException, JahiaUpdateLockException,
150             JahiaForbiddenAccessException {
151         JahiaUser theUser = jParams.getUser ();
152
153         // initalizes the hashmap
154
HashMap JavaDoc engineMap = initEngineMap (jData);
155
156         // checks if the user has the right to display the engine
157
JahiaPage thePage = (JahiaPage) engineMap.get ("thePage");
158
159         if (thePage.checkAdminAccess (theUser)) {
160             engineMap.put ("adminAccess", Boolean.TRUE);
161             engineMap.put ("enableRightView", Boolean.TRUE);
162             engineMap.put ("writeAccess", Boolean.TRUE);
163
164         } else if (thePage.checkWriteAccess (theUser)) {
165             engineMap.put ("writeAccess", Boolean.TRUE);
166         }
167
168         if (engineMap.get ("writeAccess") != null) {
169
170             // #ifdef LOCK
171
LockService lockRegistry = ServicesRegistry.getInstance ().
172                     getLockService ();
173             if (jParams.settings ().areLocksActivated ()) {
174                 LockKey lockKey = LockKey.composeLockKey (LockKey.
175                                                           UPDATE_PAGE_TYPE,
176                                                           thePage.getID (), thePage.getID ());
177                 if (lockRegistry.acquire (lockKey, jParams.getUser (),
178                                           jParams.getSessionID (),
179                                           jParams.getSession ().
180                                           getMaxInactiveInterval ())) {
181
182                     // since we cannot efficiently determine all the references
183
// to this page we do an entire cache flush.
184
/** @todo is there a better way to do this ? */
185                     CacheFactory.getHtmlCache().flush();
186                     // #endif
187
processLastScreen (jData.params (), engineMap);
188                     processCurrentScreen (jData.params (), engineMap);
189                     // #ifdef LOCK
190
} else {
191                     // Prerequisites are NOT completed ! Damned ! Redirect the JSP
192
// output to lock informations.
193
LockEngine.getInstance ().redirect (jParams, engineMap,
194                             lockKey);
195                 }
196             }
197             // #endif
198

199         } else {
200             throw new JahiaForbiddenAccessException ();
201         }
202
203         // displays the screen
204
toolBox.displayScreen (jData.params (), engineMap);
205
206         //} else {
207
// throw new JahiaUpdateLockException (thePage);
208
//}
209

210     }
211
212     /**
213      * Retrieve the engine name.
214      *
215      * @return the engine name.
216      */

217     public final String JavaDoc getName () {
218         return ENGINE_NAME;
219     }
220
221     /**
222      * processes the last screen sent by the user
223      *
224      * @param jParams a ParamBean object
225      */

226     public void processLastScreen (ParamBean jParams, HashMap JavaDoc engineMap)
227             throws JahiaException,
228             JahiaForbiddenAccessException {
229         // Sets the page
230
JahiaPage thePage = (JahiaPage) engineMap.get ("thePage");
231         // gets the last screen
232
// lastscreen = edit, rights, logs
233
String JavaDoc lastScreen = jParams.getRequest ().getParameter ("lastscreen");
234         if (lastScreen == null) {
235             return;
236             //lastScreen = "edit";
237
}
238
239         // indicates to sub engines that we are processing last screen
240
int mode = JahiaEngine.UPDATE_MODE;
241
242         // dispatches to the appropriate sub engine
243
if (lastScreen.equals ("edit")) {
244             String JavaDoc languageCode = (String JavaDoc) engineMap.get ("prevLanguageCode");
245             String JavaDoc screen = (String JavaDoc) engineMap.get("screen");
246             if (!"cancel".equals(screen)) {
247                 if (!updatePageData(jParams, engineMap, languageCode)) {
248                     // if there was an error, come back to last screen, unless we clicked on cancel
249
engineMap.put("screen", lastScreen);
250                     engineMap.put("jspSource", TEMPLATE_JSP);
251                 }
252             }
253         } else if (lastScreen.equals ("versioning")) {
254             if (engineMap.get ("writeAccess") != null
255                 ||engineMap.get ("adminAccess") != null) {
256                 engineMap.put (RENDER_TYPE_PARAM,
257                         new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
258                 // reset engine map to default value
259
engineMap.remove (ENGINE_OUTPUT_FILE_PARAM);
260
261                 releaseTreeVersioningLocks(jParams);
262
263                 // now let's reacquire the page lock for this page, as we
264
// have cleared it as part of the page subtree.
265
LockService lockRegistry = ServicesRegistry.getInstance ().
266                         getLockService ();
267                 if (jParams.settings ().areLocksActivated ()) {
268                     LockKey lockKey = LockKey.composeLockKey (LockKey.
269                                                               UPDATE_PAGE_TYPE,
270                                                               thePage.getID (), thePage.getID ());
271                     if (lockRegistry.acquire (lockKey, jParams.getUser (),
272                                               jParams.getSessionID (),
273                                               jParams.getSession ().
274                                               getMaxInactiveInterval ())) {
275
276                         // since we cannot efficiently determine all the references
277
// to this page we do an entire cache flush.
278
/** @todo is there a better way to do this ? */
279                         CacheFactory.getHtmlCache().flush();
280                         // #endif
281
// #ifdef LOCK
282
} else {
283                         // Prerequisites are NOT completed ! Damned ! Redirect the JSP
284
// output to lock informations.
285
LockEngine.getInstance ().redirect (jParams, engineMap,
286                                 lockKey);
287                     }
288                 }
289                 // #endif
290

291
292             } else {
293                 throw new JahiaForbiddenAccessException ();
294             }
295         } else if (lastScreen.equals ("rightsMgmt")) {
296             if (engineMap.get ("adminAccess") != null) {
297                 ManageRights.getInstance ().handleActions (jParams, mode,
298                         engineMap, thePage.getAclID ());
299             } else {
300                 throw new JahiaForbiddenAccessException ();
301             }
302         } else if (lastScreen.equals ("categories")) {
303             ManageCategories.getInstance ().handleActions (jParams, mode,
304                     engineMap, new ContentPageKey (thePage.getID ()),
305                     thePage.getPageTemplate (), false);
306         }
307
308     }
309
310     /**
311      * prepares the screen requested by the user
312      *
313      * @param jParams a ParamBean object
314      */

315     public void processCurrentScreen (ParamBean jParams, HashMap JavaDoc engineMap)
316             throws JahiaException,
317             JahiaForbiddenAccessException {
318         // Sets the actual field
319
JahiaPage thePage = (JahiaPage) engineMap.get ("thePage");
320
321         JahiaPageEngineTempBean pageTempBean =
322                 (JahiaPageEngineTempBean) engineMap.get ("pageTempBean");
323
324 // EntryLoadRequest entryLoadRequest
325
// = (EntryLoadRequest) engineMap.get ("entryLoadRequest");
326

327         // gets the current screen
328
// screen = edit, rights, logs
329
String JavaDoc theScreen = (String JavaDoc) engineMap.get ("screen");
330
331         // indicates to sub engines that we are processing last screen
332
int mode = JahiaEngine.LOAD_MODE;
333
334         // #ifdef LOCK
335
LockKey lockKey = LockKey.composeLockKey (LockKey.UPDATE_PAGE_TYPE,
336                 thePage.getID (), thePage.getID ());
337         LockService lockRegistry = ServicesRegistry.getInstance ().
338                 getLockService ();
339         // #endif
340

341         // dispatches to the appropriate sub engine
342
if (theScreen.equals ("edit")) {
343             loadPageData (jParams, engineMap);
344         } else if (theScreen.equals ("logs")) {
345             toolBox.loadLogData (jParams, LoggingEventListener.PAGE_TYPE,
346                     engineMap);
347         } else if (theScreen.equals ("rightsMgmt")) {
348             if (engineMap.get ("adminAccess") != null) {
349                 ManageRights.getInstance ().handleActions (jParams, mode,
350                         engineMap, thePage.getAclID ());
351             } else {
352                 throw new JahiaForbiddenAccessException ();
353             }
354         } else if (theScreen.equals ("versioning")) {
355             if (engineMap.get ("writeAccess") != null
356                 || engineMap.get ("adminAccess") != null) {
357
358                 // we don't need to free the lock when going to the versioning
359
// engine because we can re-acquire a lock we already have.
360

361                 Properties JavaDoc params = new Properties JavaDoc ();
362                 params.put ("method", "showOperationChoices");
363                 params.put ("pageid", String.valueOf (thePage.getID ()));
364                 String JavaDoc versioningURL = jParams.composeStrutsUrl (
365                         "PagesVersioning", params, null);
366
367                 engineMap.put (RENDER_TYPE_PARAM,
368                         new Integer JavaDoc (JahiaEngine.RENDERTYPE_REDIRECT));
369                 engineMap.put (ENGINE_OUTPUT_FILE_PARAM, versioningURL);
370             } else {
371                 throw new JahiaForbiddenAccessException ();
372             }
373         } else if (theScreen.equals ("categories")) {
374             ManageCategories.getInstance ().handleActions (jParams, mode,
375                     engineMap, new ContentPageKey (thePage.getID ()),
376                     thePage.getPageTemplate (), false);
377         } else if (theScreen.equals ("save") || theScreen.equals ("apply")) {
378
379             // #ifdef LOCK
380
// Did somebody steal the lock ? Panpan cucul !
381
if (jParams.settings ().areLocksActivated () &&
382                     lockRegistry.isStealedInContext (lockKey, jParams.getUser (),
383                             jParams.getSessionID ())) {
384                 engineMap.put ("screen", jParams.getRequest ().
385                         getParameter ("lastscreen"));
386                 engineMap.put ("jspSource", "apply");
387                 return;
388             }
389             // #endif
390

391             mode = JahiaEngine.SAVE_MODE;
392
393             // create one entry for each language
394
ContentPage contentPage = ServicesRegistry.getInstance ()
395                     .getJahiaPageService ().lookupContentPage (
396                             thePage.getID (), false);
397
398             //Map languageStates = contentPage.getLanguagesStates (false);
399

400             HashSet JavaDoc updatedLanguageEntries = (HashSet JavaDoc) engineMap.get (
401                     "updatedLanguageEntries");
402             if (updatedLanguageEntries == null) {
403                 updatedLanguageEntries = new HashSet JavaDoc ();
404             }
405             String JavaDoc languageCode = (String JavaDoc) engineMap.get ("languageCode");
406             if (!updatePageData (jParams, engineMap, languageCode)) {
407                 // if there was an error, come back to last screen
408
String JavaDoc lastScreen = jParams.getRequest ().getParameter (
409                         "lastscreen");
410                 if (lastScreen == null) {
411                     lastScreen = "edit";
412                 }
413                 engineMap.put ("screen", lastScreen);
414                 // already set
415
//engineMap.put( "jspSource", TEMPLATE_JSP );
416
}
417
418             thePage.setTitles (updatedLanguageEntries, pageTempBean.getTitles ());
419
420             //String pageTitle = (String)engineMap.get ("dataPageTitle");
421
//Boolean validate = (Boolean) engineMap.get ("validate");
422

423             //thePage.setTitle (pageTitle);
424
thePage.setPageTemplateID (pageTempBean.getPageTemplateID ());
425
426             String JavaDoc pageKey = (String JavaDoc)engineMap.get( "dataPageURLKey" );
427
428             if( pageKey != null && pageKey.equals( "" ) == false ){
429              thePage.setProperty( PageProperty.PAGE_URL_KEY_PROPNAME, pageKey );
430              engineMap.put( PageProperty.PAGE_URL_KEY_PROPNAME, pageKey );
431              engineMap.put("dataPageURLKey", pageKey);
432              /*List pageURLKeys = jParams.getPageURLKeys();
433              pageURLKeys.remove( pageURLKeys.size() - 1 );
434              pageURLKeys.add( pageKey );*/

435             }else{
436              thePage.removeProperty( PageProperty.PAGE_URL_KEY_PROPNAME );
437              engineMap.put( PageProperty.PAGE_URL_KEY_PROPNAME, pageKey );
438             }
439             /*String pageURLKey = jParams.getRequest().getParameter("pageURLKey");
440
441             if (pageURLKey != null) {
442                 if ("".equals(pageURLKey)) {
443                     thePage.removeProperty(PageProperty.PAGE_URL_KEY_PROPNAME);
444                 } else {
445                     thePage.setProperty(PageProperty.PAGE_URL_KEY_PROPNAME,
446                                         pageURLKey);
447                 }
448
449                 engineMap.put("dataPageURLKey", pageURLKey);
450             }*/

451
452             thePage.commitChanges (true);
453
454
455             // let's flush the sitemap to make sure the changes are updated
456
// everywhere.
457
ServicesRegistry.getInstance().getJahiaSiteMapService().resetSiteMap();
458
459             // index page title
460
int pageFieldID = ServicesRegistry.getInstance ()
461                     .getJahiaPageService ().getPageFieldID (contentPage.
462                     getID ());
463             if (pageFieldID != -1) {
464                 ServicesRegistry.getInstance ()
465                         .getJahiaSearchService ().indexField (pageFieldID, true, jParams, true);
466             }
467
468             engineMap.put ("dataPageTitle", pageTempBean.getTitle (languageCode));
469
470             // save rights
471
if (engineMap.get ("adminAccess") != null) {
472                 engineMap.put ("logObjectType",
473                         Integer.toString (LoggingEventListener.PAGE_TYPE));
474                 engineMap.put ("logObject", thePage);
475                 //ViewRights.getInstance().handleActions (jParams, mode, engineMap, thePage.getAclID());
476
ManageRights.getInstance ().handleActions (jParams, mode,
477                         engineMap, thePage.getAclID ());
478             }
479
480             // save categories
481
ManageCategories.getInstance ().handleActions (jParams, mode,
482                     engineMap,
483                     new ContentPageKey (thePage.getID ()), thePage.getPageTemplate (), false);
484
485             String JavaDoc lastScreen = jParams.getRequest ().getParameter ("lastscreen");
486             if (lastScreen != null) {
487                 logger.debug ("lastScreen=" + lastScreen);
488                 if (lastScreen.equals ("edit")) {
489
490                     // since we cannot efficiently determine all the references
491
// to this page we do an entire cache flush.
492
/** @todo is there a better way to do this ? */
493                     CacheFactory.getHtmlCache().flush();
494
495                     // fire event
496
JahiaEvent theEvent = new JahiaEvent (this, jParams, thePage);
497                     ServicesRegistry.getInstance ().getJahiaEventService ().
498                             fireSetPageProperties (theEvent);
499                 }
500             }
501             if (theScreen.equals ("apply")) {
502                 engineMap.put ("screen", lastScreen);
503             }
504             // #ifdef LOCK
505
else {
506                 if (jParams.settings ().areLocksActivated ()) {
507                     lockRegistry.release (lockKey, jParams.getUser (),
508                                           jParams.getSessionID ());
509                 }
510             }
511             // #endif
512
} else if (theScreen.equals ("cancel")) {
513             // #ifdef LOCK
514
if (jParams.settings ().areLocksActivated ()) {
515                 lockRegistry.release (lockKey, jParams.getUser (),
516                                       jParams.getSessionID ());
517                 // since we cannot efficiently determine all the references
518
// to this page we do an entire cache flush.
519
/** @todo is there a better way to do this ? */
520                 CacheFactory.getHtmlCache().flush();
521             }
522             // #endif
523
//mode = JahiaEngine.CANCEL_MODE;
524
}
525     }
526
527
528     /**
529      * inits the engine map
530      *
531      * @param jData
532      *
533      * @return a HashMap object containing all the basic values needed by an engine
534      */

535     private HashMap JavaDoc initEngineMap (JahiaData jData)
536             throws JahiaException, JahiaSessionExpirationException {
537         ParamBean jParams = jData.params ();
538
539         String JavaDoc theScreen = jParams.getRequest ().getParameter ("screen");
540
541         // gets session values
542
HttpSession JavaDoc theSession = jParams.getSession ();
543         if (theSession == null)
544             throw new JahiaSessionExpirationException ();
545
546         ContentPage contentPage = ServicesRegistry.getInstance ()
547                 .getJahiaPageService ()
548                 .lookupContentPage (jData.params ().getPage ().
549                 getID (), false);
550
551         JahiaPageEngineTempBean pageTempBean;
552
553         // Resolve language code
554
String JavaDoc languageCode = jParams.getRequest ().getParameter ("engine_lang");
555
556         if (languageCode == null) {
557             Locale JavaDoc navLocale =
558                     (Locale JavaDoc) theSession.getAttribute (ParamBean.SESSION_LOCALE);
559             languageCode = navLocale.toString ();
560         }
561
562         if (languageCode == null) {
563             languageCode = jParams.settings ().getDefaultLanguageCode ();
564         }
565
566         String JavaDoc prevLanguageCode = jParams.getRequest ().getParameter (
567                 "prev_engine_lang");
568         if (prevLanguageCode == null) {
569             prevLanguageCode = languageCode;
570         }
571
572         EntryLoadRequest entryLoadRequest =
573                 new EntryLoadRequest (EntryLoadRequest.STAGING_WORKFLOW_STATE,
574                         0, new ArrayList JavaDoc ());
575         entryLoadRequest.getLocales ().add (LanguageCodeConverters.
576                 languageCodeToLocale (languageCode));
577
578         EntryLoadRequest prevEntryLoadRequest =
579                 new EntryLoadRequest (EntryLoadRequest.STAGING_WORKFLOW_STATE,
580                         0, new ArrayList JavaDoc ());
581         prevEntryLoadRequest.getLocales ().add (LanguageCodeConverters.
582                 languageCodeToLocale (
583                         prevLanguageCode));
584
585         HashMap JavaDoc engineMap;
586         if (theScreen != null) {
587             // if no, load the container value from the session
588
engineMap = (HashMap JavaDoc) theSession.getAttribute ("jahia_session_engineMap");
589             //thePage = (JahiaPage) engineMap.get( "thePage" );
590

591             ///////////////////////////////////////////////////////////////////////////////////////
592
// FIXME -Fulco-
593
//
594
// This is a quick hack, engineMap should not be null if the session didn't
595
// expired. Maybe there are other cases where the engineMap can be null, I didn't
596
// checked them at all.
597
///////////////////////////////////////////////////////////////////////////////////////
598
if (engineMap == null) {
599                 throw new JahiaSessionExpirationException ();
600             }
601
602         } else {
603             JahiaPage thePage = jParams.getPage ();
604             theScreen = "edit";
605
606             // init engine map
607
engineMap = new HashMap JavaDoc ();
608
609             engineMap.put ("thePage", thePage);
610             pageTempBean = loadPageBeanFromRealPage (thePage);
611             engineMap.put ("pageTempBean", pageTempBean);
612             engineMap.put ("dataPageTemplateID",
613                     new Integer JavaDoc (thePage.getPageTemplateID ()));
614             PageProperty urlKeyProperty = thePage.getPageLocalProperty(PageProperty.PAGE_URL_KEY_PROPNAME);
615             if (urlKeyProperty != null) {
616                 engineMap.put ("dataPageURLKey", urlKeyProperty.getValue());
617             } else {
618                 engineMap.put ("dataPageURLKey", EMPTY_STRING);
619             }
620             engineMap.put ("validate", new Boolean JavaDoc (false));
621
622         }
623         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
624         engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
625         engineMap.put (ENGINE_URL_PARAM, jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING));
626
627         engineMap.put ("entryLoadRequest", entryLoadRequest);
628         engineMap.put ("prevEntryLoadRequest", prevEntryLoadRequest);
629         engineMap.put ("prevLanguageCode", prevLanguageCode);
630         engineMap.put ("languageCode", languageCode);
631
632         engineMap.put ("contentPage", contentPage);
633
634         pageTempBean = (JahiaPageEngineTempBean) engineMap.get ("pageTempBean");
635
636         // load page title for the processing language Code
637
jParams.setSubstituteEntryLoadRequest (entryLoadRequest);
638         String JavaDoc pageTitle = contentPage.getTitle (jParams.getEntryLoadRequest ());
639         if (pageTempBean.getTitle (languageCode) == null && (pageTitle != null)) {
640             pageTempBean.setTitle (languageCode, pageTitle);
641         }
642         jParams.resetSubstituteEntryLoadRequest ();
643         if (pageTempBean.getTitle (languageCode) != null) {
644             engineMap.put ("dataPageTitle", pageTempBean.getTitle (languageCode));
645         } else {
646             engineMap.put ("dataPageTitle", EMPTY_STRING);
647         }
648
649         // remember the requested language codes :
650
HashSet JavaDoc updatedLanguageEntries = (HashSet JavaDoc) engineMap.get (
651                 "updatedLanguageEntries");
652         if (updatedLanguageEntries == null) {
653             updatedLanguageEntries = new HashSet JavaDoc ();
654         }
655         if (!updatedLanguageEntries.contains (languageCode)) {
656             updatedLanguageEntries.add (languageCode);
657         }
658         engineMap.put ("updatedLanguageEntries", updatedLanguageEntries);
659
660         theSession.setAttribute ("jahia_session_engineMap", engineMap);
661
662         // sets screen
663
engineMap.put ("screen", theScreen);
664
665         if (theScreen.equals ("save")) {
666             engineMap.put ("jspSource", "close");
667
668         } else if (theScreen.equals ("cancel")) {
669             engineMap.put ("jspSource", "close");
670
671         } else if (theScreen.equals ("apply")) {
672             engineMap.put ("jspSource", "apply");
673
674         } else {
675             engineMap.put ("jspSource", TEMPLATE_JSP);
676         }
677
678         engineMap.put ("enableVersioning", new Boolean JavaDoc (true));
679         engineMap.put ("enableCategories", new Boolean JavaDoc (true));
680
681         // sets engineMap for JSPs
682
jParams.getRequest ().setAttribute ("engineTitle", "Page properties");
683         jParams.getRequest ().setAttribute ("org.jahia.engines.EngineHashMap",
684                 engineMap);
685
686         return engineMap;
687     }
688
689     /**
690      * loads data for the JSP file
691      *
692      * @param jParams a ParamBean object (with request and response)
693      * @param engineMap then engine map, to be forwarded to the JSP file
694      */

695     private void loadPageData (ParamBean jParams, HashMap JavaDoc engineMap)
696             throws JahiaException {
697         // check the arguments are valid
698
if (jParams == null)
699             throw new JahiaException ("Invalid parameter", "jParam argument is null!!",
700                     JahiaException.ENGINE_ERROR, JahiaException.ERROR_SEVERITY);
701
702         JahiaPage thePage = (JahiaPage) engineMap.get ("thePage");
703         JahiaUser theUser = jParams.getUser ();
704
705         // get only visibles templates
706
Enumeration JavaDoc enume= ServicesRegistry.getInstance ().
707                 getJahiaPageTemplateService ().
708                 getPageTemplates (theUser, thePage.getJahiaID (), false);
709
710         // get current page's template too even though it is desactivated
711
ContentPage contentPage = ContentPage.getPage (thePage.getID ());
712       
713         Vector JavaDoc vec = filterTemplates(jParams, contentPage, enume);
714         engineMap.put ("templateList", vec);
715
716         // existing pages, for move... not used yet
717
/*
718                  Enumeration pageTree = ServicesRegistry.getInstance().
719                 getJahiaPageService().
720                 getAllPages (thePage.getJahiaID(), PageLoadFlags.DIRECT,
721                         jParams, theUser);
722                  engineMap.put ("pageTree", pageTree);
723          */

724     }
725
726     /**
727      * Gets POST form data from the JSP file
728      * Update page data ( title, URL key, template id )
729      * @param jParams a ParamBean object (with request and response)
730      * @param engineMap then engine map, to be forwarded to the JSP file
731      *
732      * @return true if everything went okay, false if not
733      */

734     private boolean updatePageData (ParamBean jParams, HashMap JavaDoc engineMap,
735                                     String JavaDoc languageCode) throws JahiaException{
736         EngineMessages engineMessages = new EngineMessages();
737         boolean setPageTitleSuccessfull = setPageTitleIfNecessary( jParams, languageCode, engineMap );
738         boolean setPageURLKeySuccessfull = setPageURLKeyIfValidAndNotEmpty( jParams, engineMessages, engineMap );
739         setPageTemplateIDInEngineMapIfNecessary( jParams, engineMap );
740         saveMessagesIfNotEmpty( engineMessages, jParams);
741
742         if( setPageTitleSuccessfull && setPageURLKeySuccessfull ){
743             updatePageKeyCache( jParams );
744         }
745
746         return setPageTitleSuccessfull && setPageURLKeySuccessfull;
747     }
748
749     /**
750      * Remove previous cached pageID for page key.
751      * And create new cache entry Key: newPageKey_siteID, Value: pageID
752      * @param jParams
753      */

754     private void updatePageKeyCache( ParamBean jParams ){
755         removePreviousCachedEntryForPageWithID( jParams.getPageID() );
756         createNewCacheEntry( jParams );
757     }
758
759     private void createNewCacheEntry( ParamBean jParams ){
760         Cache cache = CacheFactory.getInstance().getCache( PagePropertyDB.PAGE_ID_FOR_PAGE_KEY_CACHE );
761
762
763         StringBuffer JavaDoc cacheKey = new StringBuffer JavaDoc( jParams.getRequest().getParameter( "pageURLKey" ) );
764         cacheKey.append( "_" ).append( jParams.getJahiaID() );
765         cache.put( cacheKey.toString(), new Integer JavaDoc( jParams.getPageID() ) );
766     }
767
768     private void removePreviousCachedEntryForPageWithID( int pageID ){
769         Cache cache = CacheFactory.getInstance().getCache( PagePropertyDB.PAGE_ID_FOR_PAGE_KEY_CACHE );
770         Iterator JavaDoc cachedIte = Arrays.asList( cache.keys() ).iterator();
771         StringBuffer JavaDoc currentKey = new StringBuffer JavaDoc();
772         Integer JavaDoc currentPageID = null;
773
774         while( cachedIte.hasNext() ){
775             currentKey.append( cachedIte.next() );
776             currentPageID = (Integer JavaDoc)cache.get( currentKey.toString() );
777
778             if( currentPageID.intValue() == pageID ){
779                 cache.remove( currentKey.toString() );
780             }
781
782             currentKey.delete( 0, currentKey.length() );
783         }
784     }
785
786     /**
787      * Validate and set page URL key if its present.
788      * To be valid, the key must :
789      * - not be a jahia reserved word
790      * - be composed of caracters in 0 to 9, a to z or A to Z, length min 2 max 250
791      * - not be used by another page on current jahia site
792      *
793      * The validation stops as soon as one error condition is encountered. Higher cost validation is performed last in the chain.
794      * @param jParams
795      * @param engineMessages
796      * @param engineMap
797      * @param pageTempBean
798      * @return true if the key is valid and was setted, false if empty or not valid.
799      */

800     private boolean setPageURLKeyIfValidAndNotEmpty( ParamBean jParams, EngineMessages engineMessages, Map JavaDoc engineMap )throws JahiaException{
801         String JavaDoc pageURLKey = jParams.getRequest().getParameter( "pageURLKey" );
802         if (pageURLKey == null)return false;
803         JahiaPageEngineTempBean pageTempBean = (JahiaPageEngineTempBean)engineMap.get ("pageTempBean");
804         engineMap.put("dataPageURLKey", pageURLKey);
805
806         if( ParamBean.isReservedKeyword( pageURLKey ) ){
807             engineMessages.add("pageProperties", new EngineMessage("org.jahia.engines.pages.PageProperties_Engine.urlKeyIsReservedWord.label", pageURLKey));
808             return false;
809         } else if( isValidURLKey( pageURLKey ) == false ){
810             engineMessages.add("pageProperties", new EngineMessage("org.jahia.engines.pages.PageProperties_Engine.urlKeyHasInvalidChars.label", pageURLKey));
811             return false;
812         } else if( isURLKeyAlreadyUsed( pageURLKey, pageTempBean ) == true ){
813             engineMessages.add("pageProperties", new EngineMessage("org.jahia.engines.pages.PageProperties_Engine.urlKeyIsDuplicate.label", pageURLKey));
814             return false;
815         }
816
817         return true;
818     }
819
820     /**
821      * Set page title if it was specified in request.
822      * @param jParams
823      * @param languageCode
824      * @param engineMap
825      * @return true if page title was successfully setted, false if empty
826      */

827     private boolean setPageTitleIfNecessary( ParamBean jParams, String JavaDoc languageCode, Map JavaDoc engineMap ){
828         String JavaDoc pageTitle = jParams.getRequest ().getParameter ("pageTitle");
829         if( pageTitle == null )return false;
830         JahiaPageEngineTempBean pageTempBean = (JahiaPageEngineTempBean)engineMap.get ("pageTempBean");
831         pageTempBean.setTitle (languageCode, pageTitle);
832         engineMap.put ("validate", Boolean.valueOf( jParams.getRequest().getParameter( "validate" ) != null ) );
833         return true;
834
835     }
836
837     /**
838      * Set page template ID if it was specified in request.
839      * @param jParams
840      * @param engineMap
841      */

842     private void setPageTemplateIDInEngineMapIfNecessary( ParamBean jParams, Map JavaDoc engineMap ){
843         String JavaDoc pageDef = jParams.getRequest ().getParameter ("pageTemplate");
844
845         if( pageDef == null )return;
846         JahiaPageEngineTempBean pageTempBean = (JahiaPageEngineTempBean)engineMap.get ("pageTempBean");
847         int pageTemplateID = Integer.parseInt (pageDef);
848         pageTempBean.setPageTemplateID (pageTemplateID);
849         engineMap.put ("dataPageTemplateID", new Integer JavaDoc (pageTemplateID));
850         engineMap.put ("validate", Boolean.valueOf( jParams.getRequest().getParameter( "validate" ) != null ) );
851     }
852
853     private void saveMessagesIfNotEmpty( EngineMessages engineMessages, ParamBean jParams ){
854          if ( engineMessages.isEmpty() )return;
855          engineMessages.saveMessages(jParams.getRequest());
856     }
857
858     private boolean isURLKeyAlreadyUsed( String JavaDoc urlKey, JahiaPageEngineTempBean pageTempBean )throws JahiaException{
859        /* try{
860         Iterator propIter = ServicesRegistry.getInstance().getJahiaPageService().getPagePropertiesByValue( urlKey ).iterator();
861
862         while (propIter.hasNext()) {
863             PageProperty curProperty = (PageProperty) propIter.next();
864
865             if ((curProperty.getName().equals(PageProperty.PAGE_URL_KEY_PROPNAME)) &&
866                 (curProperty.getPageID() != pageTempBean.getID()))
867             {
868                 return true;
869             }
870         }
871         }catch( JahiaException jex ){}
872         return false;*/

873
874         return ServicesRegistry.getInstance().getJahiaPageService().isKeyAlreadyUsedInSiteWithID( urlKey, pageTempBean.getSiteID(), pageTempBean.getID() );
875     }
876
877     private boolean isValidURLKey( String JavaDoc urlKey ){
878
879         return Pattern.compile( "^[a-zA-Z_0-9\\-\\.]{0,250}$" ).matcher( urlKey ).matches();
880     }
881
882     /**
883      * loads the page cache bean with info from an existing JahiaPage
884      *
885      * @return a PageBean to use as cache for the page info
886      */

887     private JahiaPageEngineTempBean loadPageBeanFromRealPage (JahiaPage theRealPage) {
888
889         logger.debug ("Making PageBean from REAL Page...");
890         StringBuffer JavaDoc pageAttribute = new StringBuffer JavaDoc (" jahiaID : [");
891         pageAttribute.append (theRealPage.getJahiaID ());
892         pageAttribute.append ("]\n");
893         pageAttribute.append (" parentID : [");
894         pageAttribute.append (theRealPage.getParentID ());
895         pageAttribute.append ("]\n");
896         pageAttribute.append (" pageType : [");
897         pageAttribute.append (theRealPage.getPageType ());
898         pageAttribute.append ("]\n");
899         pageAttribute.append (" title : [");
900         pageAttribute.append (theRealPage.getTitle ());
901         pageAttribute.append ("]\n");
902         pageAttribute.append (" pageTemplateID: [");
903         pageAttribute.append (theRealPage.getPageTemplateID ());
904         pageAttribute.append ("]\n");
905         pageAttribute.append (" remoteURL : [");
906         pageAttribute.append (theRealPage.getRemoteURL ());
907         pageAttribute.append ("]\n");
908         pageAttribute.append (" pageLinkID : [");
909         pageAttribute.append (theRealPage.getPageLinkID ());
910         pageAttribute.append ("]\n");
911         pageAttribute.append (" creator : [");
912         pageAttribute.append (theRealPage.getCreator ());
913         pageAttribute.append ("]\n");
914
915         logger.debug (pageAttribute.toString ());
916
917         JahiaPageEngineTempBean thePage = new JahiaPageEngineTempBean (
918                 theRealPage.getID (),
919                 theRealPage.getJahiaID (),
920                 theRealPage.getParentID (),
921                 theRealPage.getPageType (),
922                 theRealPage.getPageTemplateID (),
923                 theRealPage.getRemoteURL (),
924                 theRealPage.getPageLinkID (),
925                 theRealPage.getCreator (),
926                 -1 // linked field not used
927
);
928         return thePage;
929     }
930
931     private void releaseTreeVersioningLocks (ParamBean jParams)
932             throws JahiaException {
933         if (jParams.settings ().areLocksActivated ()) {
934             ArrayList JavaDoc acquiredPageLocks = (ArrayList JavaDoc) jParams.getSession().getAttribute(PagesVersioningAction.SESSION_VERSIONING_LOCK_LIST);
935             if (acquiredPageLocks == null) {
936                 return;
937             }
938             HtmlCache htmlCache = CacheFactory.getHtmlCache();
939
940             // Lock all page site if possible.
941
LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
942             Iterator JavaDoc acquiredPageIter = acquiredPageLocks.iterator();
943             while (acquiredPageIter.hasNext()) {
944                 int curPageID = ((Integer JavaDoc) acquiredPageIter.next()).intValue();
945                 LockKey lockKey = LockKey.composeLockKey (LockKey.UPDATE_PAGE_TYPE,
946                                                           curPageID, curPageID);
947                 lockRegistry.release (lockKey, jParams.getUser (), jParams.getSessionID ());
948                 htmlCache.invalidatePageEntries(Integer.toString(curPageID),jParams.getEntryLoadRequest().getWorkflowState());
949             }
950         }
951     }
952     /**
953      * utility method
954      * @param s the long string
955      * @return a Set of string
956      */

957      private Set JavaDoc getStringToSet(final String JavaDoc s) {
958          final Set JavaDoc vlist = new HashSet JavaDoc();
959          final StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(s, ",");
960          while (tok.hasMoreTokens()) {
961              final String JavaDoc v = tok.nextToken().trim();
962              vlist.add(v);
963          }
964          return vlist;
965      }
966      
967      private Vector JavaDoc filterTemplates(ParamBean jParams, ContentPage contentPage,
968             Enumeration JavaDoc tlist) throws JahiaException {
969         Set JavaDoc constraintTemplates = new HashSet JavaDoc();// vector of templates
970
// constraint
971

972         ContentObject parentField = contentPage.getParent(jParams.getUser(),
973                 jParams.getEntryLoadRequest(), jParams.getOperationMode());
974         if (parentField != null) {
975             JahiaFieldDefinition fieldDef = JahiaFieldDefinitionsRegistry
976                     .getInstance().getDefinition(
977                             parentField.getDefinitionID(jParams
978                                     .getEntryLoadRequest()));
979             ContentPage parentPage = ((ContentPageField) parentField).getPage();
980             int pageDefID = parentPage != null ? parentPage
981                     .getPageTemplateID(jParams) : contentPage
982                     .getPageTemplateID(jParams);
983             JahiaFieldSubDefinition fieldSubDef = (JahiaFieldSubDefinition) fieldDef
984                     .getSubDefs().get(new Integer JavaDoc(pageDefID));
985             String JavaDoc defaultValue = fieldSubDef.getDefaultValue();
986
987             // requested
988
if (defaultValue.indexOf("[") != -1) {
989                 int p1 = defaultValue.indexOf("[");
990                 int p2 = defaultValue.lastIndexOf("]");
991                 String JavaDoc tList = defaultValue.substring(p1, p2 + 1);
992                 defaultValue = StringUtils.replace(defaultValue, tList, "");
993
994                 tList = tList.substring(1, tList.length() - 1);
995                 constraintTemplates = getStringToSet(tList);
996                 logger.debug("tlist: " + constraintTemplates);
997             }
998         }
999
1000        Vector JavaDoc all = new Vector JavaDoc();
1001        Vector JavaDoc constraint = new Vector JavaDoc();
1002        int checkcount = constraintTemplates.size();
1003        while (tlist.hasMoreElements()) {
1004            JahiaPageDefinition t = (JahiaPageDefinition) tlist.nextElement();
1005            if (t.isAvailable()) {
1006                all.add(t);
1007            }
1008            String JavaDoc templatename = t.getName();
1009            if (constraintTemplates.contains(templatename)) {
1010                logger.debug("found requested templates:" + templatename);
1011                checkcount--;
1012                constraint.add(t);
1013            }
1014        }
1015
1016        Vector JavaDoc vec = (constraintTemplates.size() > 0 && checkcount == 0 ? constraint
1017                : all);
1018
1019        EntryLoadRequest loadRequest = new EntryLoadRequest(
1020                EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0, jParams
1021                        .getEntryLoadRequest().getLocales());
1022        // active page def
1023
JahiaPageDefinition activePageDef = contentPage
1024                .getPageTemplate(loadRequest);
1025        JahiaPageDefinition currentPageDef = contentPage
1026                .getPageTemplate(jParams);
1027
1028        if (activePageDef != null && !vec.contains(activePageDef))
1029            vec.add(activePageDef);
1030        if (currentPageDef != null && !vec.contains(currentPageDef))
1031            vec.add(currentPageDef);
1032
1033        // sort it
1034
if (vec.size() > 1) {
1035            Collections.sort(vec, (Comparator JavaDoc) vec.get(0));
1036        }
1037
1038        return vec;
1039    }
1040}
1041
Popular Tags