KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > shared > Page_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  * ----- BEGIN LICENSE BLOCK -----
15  * Version: JCSL 1.0
16  *
17  * The contents of this file are subject to the Jahia Community Source License
18  * 1.0 or later (the "License"); you may not use this file except in
19  * compliance with the License. You may obtain a copy of the License at
20  * http://www.jahia.org/license
21  *
22  * Software distributed under the License is distributed on an "AS IS" basis,
23  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
24  * for the rights, obligations and limitations governing use of the contents
25  * of the file. The Original and Upgraded Code is the Jahia CMS and Portal
26  * Server. The developer of the Original and Upgraded Code is JAHIA Ltd. JAHIA
27  * Ltd. owns the copyrights in the portions it created. All Rights Reserved.
28  *
29  * The Shared Modifications are Jahia View Helper.
30  *
31  * The Developer of the Shared Modifications is Jahia Solution S�rl.
32  * Portions created by the Initial Developer are Copyright (C) 2002 by the
33  * Initial Developer. All Rights Reserved.
34  *
35  * Contributor(s):
36  * 15-AUG-2003, Jahia Solutions Sarl: Fulco Houkes
37  *
38  * ----- END LICENSE BLOCK -----
39  */

40
41
42 package org.jahia.engines.shared;
43
44 import java.util.Collections JavaDoc;
45 import java.util.Enumeration JavaDoc;
46 import java.util.HashMap JavaDoc;
47 import java.util.Hashtable JavaDoc;
48 import java.util.Vector JavaDoc;
49
50 import org.apache.log4j.Logger;
51 import org.jahia.data.containers.JahiaContainer;
52 import org.jahia.data.fields.JahiaField;
53 import org.jahia.data.fields.JahiaFieldDefinitionProperties;
54 import org.jahia.engines.JahiaEngine;
55 import org.jahia.engines.JahiaEngineTools;
56 import org.jahia.engines.selectpage.SelectPage_Engine;
57 import org.jahia.exceptions.JahiaException;
58 import org.jahia.exceptions.JahiaTemplateNotFoundException;
59 import org.jahia.exceptions.JahiaUpdateLockException;
60 import org.jahia.params.ParamBean;
61 import org.jahia.registries.ServicesRegistry;
62 import org.jahia.services.acl.JahiaBaseACL;
63 import org.jahia.services.fields.ContentPageField;
64 import org.jahia.services.pages.ContentPage;
65 import org.jahia.services.pages.JahiaPage;
66 import org.jahia.services.pages.JahiaPageBaseService;
67 import org.jahia.services.pages.JahiaPageDefinition;
68 import org.jahia.services.sites.SiteLanguageSettings;
69 import org.jahia.services.version.EntryLoadRequest;
70 import org.jahia.services.version.StateModificationContext;
71 import java.io.UnsupportedEncodingException JavaDoc;
72 import org.jahia.bin.Jahia;
73 import org.jahia.services.containers.ContentContainer;
74 import org.jahia.content.ContentObject;
75 import org.jahia.exceptions.JahiaPageNotFoundException;
76
77 public class Page_Field {
78
79     public static final String JavaDoc READONLY_JSP = "/jsp/jahia/engines/shared/readonly_page_field.jsp";
80     public static final String JavaDoc ACCESSDENIED_JSP = "/jsp/jahia/engines/shared/accessdenied_page_field.jsp";
81     public static final String JavaDoc CREATE_PAGE = "createPage";
82     // Page update consists to change templae, change title or change (if possible)
83
// page type.
84
public static final String JavaDoc UPDATE_PAGE = "updatePage";
85     public static final String JavaDoc LINK_JAHIA_PAGE = "linkJahiaPage";
86     public static final String JavaDoc LINK_URL = "linkURL";
87     public static final String JavaDoc MOVE_PAGE = "movePage";
88     public static final String JavaDoc COPY_PAGE = "copyPage";
89     public static final String JavaDoc RESET_LINK = "removeLink";
90
91     private static final int MAX_PAGETITLE_LENGTH = 250;
92
93     private static Page_Field instance;
94     private static final String JavaDoc[] DEFAULT_OPERATION = {UPDATE_PAGE, LINK_JAHIA_PAGE, LINK_URL};
95     private static final String JavaDoc JSP_FILE = "/jsp/jahia/engines/shared/page_field.jsp";
96
97
98
99     /**
100      * Retrieves the unique instance of this class.
101      *
102      * @return the unique instance of this class
103      */

104     public static synchronized Page_Field getInstance() {
105         if (instance == null) {
106             instance = new Page_Field();
107         }
108         return instance;
109     }
110
111
112     /**
113      * Handles the field actions
114      *
115      * @param jParams a ParamBean object
116      * @param modeInt the mode, according to JahiaEngine
117      * @param engineMap the engine map prepared from the parent engine.
118      * @return true if everything went okay, false if not
119      * @throws JahiaUpdateLockException
120      * @throws JahiaException
121      * @see org.jahia.engines.JahiaEngine
122      */

123     public boolean handleField( ParamBean jParams, Integer JavaDoc modeInt, HashMap JavaDoc engineMap )
124             throws JahiaException, JahiaUpdateLockException {
125         // @todo : find a better way
126
String JavaDoc processingLanguageCode = (String JavaDoc)engineMap.get(JahiaEngine.PROCESSING_LANGUAGECODE);
127         EntryLoadRequest entryLoadRequest = (EntryLoadRequest)engineMap.get("entryLoadRequest");
128         entryLoadRequest.setFirstLocale(processingLanguageCode);
129         jParams.setSubstituteEntryLoadRequest(entryLoadRequest);
130
131         JahiaField theField = (JahiaField)engineMap.get("theField");
132
133         switch (modeInt.intValue()) {
134             case (JahiaEngine.LOAD_MODE) :
135                 logger.debug("Loading pagefield");
136                 return composeEngineMap( jParams, engineMap, theField );
137             case (JahiaEngine.UPDATE_MODE) :
138                 logger.debug("Updating pagefield");
139                 return getFormData( jParams, engineMap, theField );
140             case (JahiaEngine.SAVE_MODE) :
141                 logger.debug("Saving pagefield");
142                 return saveData( jParams, engineMap, theField );
143         }
144         jParams.resetSubstituteEntryLoadRequest();
145         return false;
146     }
147
148     /**
149      * Remove all page beans from session before calling this engine for adding
150      * container containing page field for example.
151      *
152      * @param jParams The ParamBean object
153      * @throws JahiaException
154      *
155      * @todo : Because the field ID numbering for new field creation are <0,
156      * there is no explicit limitation for downcounting the number of them. So
157      * we actually admit 5 (can be a parameter !) page fields in a container. So,
158      * the major cases should be cover.
159      */

160     public static final void resetPageBeanSession(ParamBean jParams)
161             throws JahiaException {
162         jParams.getSession().removeAttribute("Page_Field.PageBeans");
163     }
164
165     /**
166      * Initialize the page bean object before calling the engine.
167      * @param jParams A ParamBeam object
168      * @param theField The page field ID corresponding to the field to edit
169      * @throws JahiaException
170      */

171     public static final void initPageBeanSession(ParamBean jParams, JahiaField theField)
172             throws JahiaException {
173         HashMap JavaDoc pageBeans =
174                 (HashMap JavaDoc)jParams.getSession().getAttribute("Page_Field.PageBeans");
175        if ( pageBeans != null ){
176           pageBeans.remove(theField.getDefinition().getName());
177        }
178     }
179
180     /**
181      * composes engine hash map
182      *
183      * @param jParams a ParamBean object
184      * @param engineMap the engine hashmap
185      * @param theField the field we are working on
186      * @return true if everything went okay, false if not
187      * @throws JahiaException
188      */

189     private boolean composeEngineMap( ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField )
190             throws JahiaException {
191
192         logger.debug("Start compose Jahia page field engine map");
193
194         boolean editable = false;
195         JahiaContainer theContainer = (JahiaContainer)engineMap.get("theContainer");
196         if ( theContainer == null ){
197             // in case of a field , not a field in a container
198
editable = true;
199         } else {
200             HashMap JavaDoc ctnListFieldAcls = (HashMap JavaDoc) engineMap
201                     .get("ctnListFieldAcls");
202
203             if (theContainer.getListID() != 0 && ctnListFieldAcls != null
204                     && ctnListFieldAcls.size() > 0) {
205                 JahiaBaseACL acl = JahiaEngineTools.getCtnListFieldACL(
206                         ctnListFieldAcls, theField.getID());
207                 if (acl != null) {
208                     editable = acl.getPermission(jParams.getUser(),
209                             JahiaBaseACL.WRITE_RIGHTS, true);
210                 }
211             } else {
212                 editable = true;
213             }
214         }
215         String JavaDoc output = "";
216         
217         String JavaDoc forward = theField.getDefinition()
218                        .getProperty(JahiaFieldDefinitionProperties.FIELD_UPDATE_JSP_FILE_PROP);
219         if ( forward == null ){
220             forward = Page_Field.JSP_FILE;
221             if ( !editable ){
222                 forward = Page_Field.READONLY_JSP;
223             }
224         }
225    
226         if (editable) {
227             JahiaPageEngineTempBean pageBean = composePage(jParams, engineMap, theField);
228             if (pageBean == null) {
229                 // this can happen if we don't have the rights to the page
230
// or if the page field has a corrupted value.
231
output = ServicesRegistry.getInstance().getJahiaFetcherService().fetchServlet( jParams, ACCESSDENIED_JSP );
232                 engineMap.put( "fieldForm", output );
233                 return true;
234             }
235             int selectedPageID = pageBean.getPageLinkID();
236             if (jParams.getRequest().getParameter("shouldSetPageLinkID") != null) {
237                 selectedPageID = SelectPage_Engine.getInstance().getSelectedPageID(jParams.getSession());
238             }
239             if (jParams.getRequest().getParameter("pageMoveDeleteOldContainer") != null) {
240                 String JavaDoc val = jParams.getRequest().getParameter("pageMoveDeleteOldContainer");
241                 pageBean.setDeleteOldContainer("1".equals(val));
242             }
243
244             if (selectedPageID != pageBean.getPageLinkID()) {
245                 pageBean.setPageLinkID(selectedPageID);
246                 if (selectedPageID != -1) {
247                   ContentPage contentPage = JahiaPageBaseService.getInstance().
248                         lookupContentPage(selectedPageID, jParams.getEntryLoadRequest(), false);
249                   Hashtable JavaDoc titles = contentPage.getTitles(ContentPage.LAST_UPDATED_TITLES);
250                   Enumeration JavaDoc titleKeys = titles.keys();
251                   while (titleKeys.hasMoreElements()) {
252                       String JavaDoc languageCode = (String JavaDoc)titleKeys.nextElement();
253                       String JavaDoc title = pageBean.getTitle(languageCode);
254                       if ((title == null) || (title.length()==0)) {
255                           pageBean.setTitle(languageCode, (String JavaDoc)titles.get(languageCode));
256                       }
257                   }
258                 } else {
259                     pageBean.setTitles(new Hashtable JavaDoc());
260                 }
261             }
262
263             boolean templateNotFound = false;
264
265             // template list
266
Enumeration JavaDoc enumeration = ServicesRegistry.getInstance().getJahiaPageTemplateService().
267                                getPageTemplates(jParams.getUser(), pageBean.getSiteID(), false); // show only visible templates
268

269             // get current page's template too even though it is desactivated
270
if ( pageBean.getID() > 0 ){
271                 ContentPage contentPage = null;
272                 try {
273                     contentPage = ContentPage.getPage(pageBean.getID());
274                 } catch ( JahiaTemplateNotFoundException tnfe ){
275                     logger.debug("Template not found for page[" + pageBean.getID() +"], try return a ContentPage without template");
276                     contentPage = JahiaPageBaseService.getInstance().
277                         lookupContentPage(pageBean.getID(), jParams.getEntryLoadRequest(), false);
278                 }
279
280                 EntryLoadRequest loadRequest =
281                         new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE,0,
282                         jParams.getEntryLoadRequest().getLocales());
283
284                 // active page def
285
JahiaPageDefinition activePageDef = contentPage.getPageTemplate(loadRequest);
286
287                 JahiaPageDefinition currentPageDef = null;
288                 try {
289                     currentPageDef = ServicesRegistry.getInstance().getJahiaPageTemplateService()
290                         .lookupPageTemplate(pageBean.getPageTemplateID());
291                 } catch (JahiaTemplateNotFoundException tnfe){
292                     logger.debug("Current Template not found for page[" + pageBean.getID() +"]");
293                     if ( pageBean.getPageType() == JahiaPage.TYPE_DIRECT ){
294                         templateNotFound = true;
295                     }
296                 }
297
298                 boolean addActivePageDef = true;
299                 boolean addCurrentPageDef = true;
300
301                 Vector JavaDoc vec = new Vector JavaDoc();
302                 while( enumeration.hasMoreElements() ){
303                     JahiaPageDefinition tmpPageDef = (JahiaPageDefinition)enumeration.nextElement();
304                     if ( activePageDef != null && (tmpPageDef.getID() == activePageDef.getID()) ){
305                         addActivePageDef = false;
306                     }
307                     if ( currentPageDef != null && (tmpPageDef.getID() == currentPageDef.getID()) ){
308                         addCurrentPageDef = false;
309                     }
310                     vec.add( tmpPageDef );
311                 }
312
313                 if ( addActivePageDef && activePageDef != null ){
314                     vec.add(activePageDef);
315                 }
316                 if ( addCurrentPageDef && currentPageDef != null ){
317                     if ( activePageDef == null
318                          || activePageDef.getID() != currentPageDef.getID() ){
319                         vec.add(currentPageDef);
320                     }
321                 }
322
323                 // sort it
324
if ( currentPageDef != null ){
325                     Collections.sort(vec,currentPageDef);
326                 } else if ( activePageDef != null ){
327                     Collections.sort(vec,activePageDef);
328                 }
329                 enumeration = vec.elements();
330             }
331
332             engineMap.put("templateNotFound", new Boolean JavaDoc(templateNotFound));
333             engineMap.put("templateList", enumeration);
334             HashMap JavaDoc selectPageURLParams = new HashMap JavaDoc();
335             selectPageURLParams.put(SelectPage_Engine.OPERATION, pageBean.getOperation());
336             selectPageURLParams.put(SelectPage_Engine.PARENT_PAGE_ID, new Integer JavaDoc(pageBean.getParentID()));
337             selectPageURLParams.put(SelectPage_Engine.PAGE_ID, new Integer JavaDoc(pageBean.getID()));
338             String JavaDoc selectPageURL = SelectPage_Engine.getInstance().renderLink(jParams, selectPageURLParams);
339             engineMap.put("selectPageURL", selectPageURL);
340             output = ServicesRegistry.getInstance().getJahiaFetcherService().fetchServlet( jParams, forward );
341         } else {
342             composePage(jParams, engineMap, theField);
343             output = ServicesRegistry.getInstance().getJahiaFetcherService().fetchServlet( jParams, forward );
344         }
345         engineMap.put( "fieldForm", output );
346         return true;
347     }
348
349     /**
350      * gets POST data from the form and saves it in session
351      *
352      * @param jParams a ParamBean object
353      * @param engineMap the engine hashmap
354      * @param theField the field we are working on
355      * @return true if everything went okay, false if not
356      * @throws JahiaException
357      */

358     private boolean getFormData (ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField)
359             throws JahiaException {
360
361         logger.debug("Gets POST data from the form and saves it in session");
362
363         HashMap JavaDoc pageBeans = (HashMap JavaDoc)jParams.
364                 getSession().getAttribute("Page_Field.PageBeans");
365         JahiaPageEngineTempBean pageBean =
366                 (JahiaPageEngineTempBean)pageBeans.get(theField.getDefinition().getName());
367
368         if (pageBean == null) {
369             // this can happen if we are processing a page field for a page
370
// that denies access to it or in the case of a page field that
371
// has a value to an invalid page ID.
372
return true;
373         }
374
375         String JavaDoc operation = jParams.getParameter("operation"); // Value from FORM
376
// Invalidate the last seleted page when operatin change.
377
if (pageBean.getOperation() == null ||
378             !pageBean.getOperation().equals(operation)) {
379             pageBean.setPageLinkID(-1);
380         }
381         pageBean.setOperation(operation);
382
383         String JavaDoc title = jParams.getRequest().getParameter("page_title");
384         // we must check the length here, by correctly handling multibyte
385
// characters in the full byte length (unfortunately some databases
386
// such as Oracle using byte length instead of character length).
387
String JavaDoc encoding = jParams.getRequest().getCharacterEncoding();
388         if (encoding == null) {
389             encoding = Jahia.getSettings().getDefaultResponseBodyEncoding();
390         }
391         try {
392             int byteLength = title.getBytes(encoding).length;
393             while (byteLength > MAX_PAGETITLE_LENGTH) {
394                 logger.debug("Byte length of field value is over limit, truncating one byte from end...");
395                 // here we remove one character at a time because the byte
396
// length of a character may vary a lot.
397
title = title.substring(0, title.length() -1);
398                 byteLength = title.getBytes(encoding).length;
399             }
400         } catch (UnsupportedEncodingException JavaDoc uee) {
401             logger.error("Error while calculating byte length of field value for encoding " + encoding, uee);
402         }
403
404         String JavaDoc languageCode = (String JavaDoc)engineMap.get(JahiaEngine.PROCESSING_LANGUAGECODE);
405         if (CREATE_PAGE.equals(operation) || UPDATE_PAGE.equals(operation)) {
406             int templateID = Integer.parseInt(jParams.getRequest().getParameter("template_id"));
407             pageBean.setPageTemplateID(templateID);
408             pageBean.setPageType(JahiaPage.TYPE_DIRECT);
409         } else if (LINK_URL.equals(operation)) {
410             String JavaDoc remoteURL = jParams.getRequest().getParameter("remote_url");
411             pageBean.setRemoteURL(remoteURL);
412             pageBean.setPageType(JahiaPage.TYPE_URL);
413             if ((title == null) || ("".equals(title))) {
414                 if (remoteURL.startsWith("http://")) {
415                     title = remoteURL.substring("http://".length());
416                 } else if (remoteURL.startsWith("https://")) {
417                     title = remoteURL.substring("https://".length());
418                 } else {
419                     title = remoteURL;
420                 }
421                 if ("".equals(title)) {
422                     title = "Undefined URL";
423                 }
424             }
425         } else if (LINK_JAHIA_PAGE.equals(operation) ||
426                    MOVE_PAGE.equals(operation)) {
427             int selectedPageID = pageBean.getPageLinkID();
428             if (jParams.getRequest().getParameter("shouldSetPageLinkID") != null) {
429                 selectedPageID = SelectPage_Engine.getInstance().getSelectedPageID(jParams.getSession());
430             }
431             pageBean.setPageLinkID(selectedPageID);
432             pageBean.setPageType(JahiaPage.TYPE_LINK);
433             if ("".equals(title) && selectedPageID > -1) {
434                 ContentPage contentPage = JahiaPageBaseService.getInstance().
435                         lookupContentPage(selectedPageID, jParams.getEntryLoadRequest(), false);
436                 Hashtable JavaDoc titles = contentPage.getTitles(ContentPage.LAST_UPDATED_TITLES);
437                 pageBean.setTitle(languageCode, (String JavaDoc)titles.get(languageCode));
438             }
439         } else if (COPY_PAGE.equals(operation)) {
440             /** @todo : not implemented */
441         }
442
443         if (jParams.getRequest().getParameter("pageMoveDeleteOldContainer") != null) {
444             String JavaDoc val = jParams.getRequest().getParameter("pageMoveDeleteOldContainer");
445             pageBean.setDeleteOldContainer("1".equals(val));
446         }
447
448         // Verify if the page title is shared
449
String JavaDoc sharedTitle = jParams.getRequest().getParameter("shared_title");
450         if (sharedTitle != null) {
451             // Set the same title to all languages
452
Vector JavaDoc languageSettings = jParams.getSite().getLanguageSettings();
453             Enumeration JavaDoc languageEnum = languageSettings.elements();
454             while (languageEnum.hasMoreElements()) {
455                 String JavaDoc langCode = ((SiteLanguageSettings)languageEnum.nextElement()).getCode();
456                 pageBean.setTitle(langCode, title);
457             }
458             pageBean.sharedTitle(true);
459         } else if (pageBean.isSharedTitle()) { // V removed from the checkbox.
460
pageBean.sharedTitle(false);
461         }
462         if (title != null) {
463             pageBean.setTitle(languageCode, title);
464         }
465
466         return true;
467     }
468
469     /**
470      * saves data in datasource
471      *
472      * @param jParams a ParamBean object
473      * @param engineMap the engine hashmap
474      * @param theField the field we are working on
475      * @return true if everything went okay, false if not
476      * @throws JahiaException
477      */

478     private boolean saveData( ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField )
479             throws JahiaException {
480
481         logger.debug("Save data from the session");
482         ContentPage contentPage = null;
483
484         HashMap JavaDoc pageBeans = (HashMap JavaDoc)jParams.
485                 getSession().getAttribute("Page_Field.PageBeans");
486
487         JahiaPageEngineTempBean pageBean = null;
488         if ( pageBeans != null ) {
489             pageBean =
490                 (JahiaPageEngineTempBean)pageBeans.get(theField.getDefinition().getName());
491         }
492
493         if ( pageBean == null ){
494             // In the case we never went to the page_field engine or if we
495
// are processing a field for a page we don't have access to or
496
// even in the case where the page field points to an invalid
497
// page ID.
498
return true;
499         }
500
501         String JavaDoc operation = pageBean.getOperation();
502         if (CREATE_PAGE.equals(operation) ||
503             LINK_JAHIA_PAGE.equals(operation) ||
504             LINK_URL.equals(operation)) {
505             String JavaDoc processingLanguageCode = (String JavaDoc)engineMap.get(JahiaEngine.PROCESSING_LANGUAGECODE);
506             JahiaPage jahiaPage;
507             if (theField.getObject() == null) { // Is it a new page ?
508
if ((LINK_JAHIA_PAGE.equals(operation)) &&
509                     (pageBean.getPageLinkID() == -1)) {
510                     // this means we have never initialized the page we want
511
// to link to.
512
return false;
513                 }
514                 jahiaPage = ServicesRegistry.getInstance().getJahiaPageService().
515                             createPage(pageBean.getSiteID(),
516                                        pageBean.getParentID(),
517                                        pageBean.getPageType(),
518                                        pageBean.getTitle(processingLanguageCode),
519                                        pageBean.getPageTemplateID(),
520                                        pageBean.getRemoteURL(),
521                                        pageBean.getPageLinkID(),
522                                        pageBean.getCreator(),
523                                        theField.getAclID(),
524                                        jParams);
525             } else {
526
527                 jahiaPage = (JahiaPage)theField.getObject();
528                 if (LINK_JAHIA_PAGE.equals(operation)) {
529                     jahiaPage.setPageLinkID(pageBean.getPageLinkID());
530                     // Has the page change to a LINK or URL page type. In this case
531
// the ACL has to be set to the appropriate ID.
532
if (jahiaPage.getPageType() == JahiaPage.TYPE_DIRECT ||
533                         jahiaPage.getPageType() == JahiaPage.TYPE_URL) {
534                         ContentPage linkContentPage = null;
535
536                         try {
537                             linkContentPage =
538                                 ServicesRegistry.getInstance().getJahiaPageService().
539                                 lookupContentPage(pageBean.getPageLinkID(), false);
540                             // The old ACL always exists in the case we return to a
541
// direct page type. See operation CHANGE_TEMPLATE
542
jahiaPage.setAclID(linkContentPage.getAclID());
543
544                             ServicesRegistry.getInstance().getJahiaSiteMapService().
545                                 removeUserSiteMap(jParams.getUser().getUserKey());
546                         } catch (JahiaPageNotFoundException jpnfe) {
547                             // linked page was not found, or set to -1, let's
548
// not update the change.
549
}
550                     }
551                 } else if (LINK_URL.equals(operation)) {
552                     jahiaPage.setRemoteURL(pageBean.getRemoteURL());
553                     // Has the page change to an URL page type ? In this case (re)create an ACL.
554
if (jahiaPage.getPageType() == JahiaPage.TYPE_LINK) {
555                         JahiaBaseACL acl = new JahiaBaseACL();
556                         acl.create(theField.getAclID());
557                         /** @todo reset the previous ACL entry if needed */
558                         jahiaPage.setAclID(acl.getID());
559                     }
560                     ServicesRegistry.getInstance().getJahiaSiteMapService().
561                             removeUserSiteMap(jParams.getUser().getUserKey());
562                 }
563                 jahiaPage.setPageType(pageBean.getPageType());
564             }
565             theField.setValue(Integer.toString(jahiaPage.getID()));
566             theField.setObject(jahiaPage);
567             theField.save(jParams);
568             contentPage = ServicesRegistry.getInstance().getJahiaPageService().
569                                lookupContentPage(jahiaPage.getID(), false);
570
571         } else if (UPDATE_PAGE.equals(operation)) {
572             // Set the object field
573

574             JahiaPage jahiaPage = ServicesRegistry.getInstance().getJahiaPageService().
575                                   lookupPage(pageBean.getID(), jParams.getEntryLoadRequest(),
576                                   jParams.getOperationMode(), jParams.getUser(),false);
577
578             // Has the page change to a DIRECT page type ? In this case (re)create an ACL.
579
if (jahiaPage .getPageType() == ContentPage.TYPE_LINK) {
580                 JahiaBaseACL acl = new JahiaBaseACL();
581                 acl.create(theField.getAclID());
582                 /** @todo reset the previous ACL entry if needed */
583                 jahiaPage.setAclID(acl.getID());
584                 ServicesRegistry.getInstance().getJahiaSiteMapService().
585                         removeUserSiteMap(jParams.getUser().getUserKey());
586             }
587             jahiaPage.setPageTemplateID(pageBean.getPageTemplateID());
588             theField.setObject(jahiaPage);
589
590             // Save the field modifications
591
theField.save(jParams);
592
593             // For save title changes
594
contentPage = ServicesRegistry.getInstance().getJahiaPageService().
595                                lookupContentPage(jahiaPage.getID(), false);
596
597         } else if (MOVE_PAGE.equals(operation)) {
598
599             // Get the cache instance BEFORE applying any modification in case the cache cannot
600
// be found for any mysterious reason ;o) THIS SHOULD STAY THE FIRST ACTION TO
601
// PREVENT THE NECESSITY OF ROLLLING BACK PREVIOUS OPERATIONS IN CASE THE CACHE
602
// IN NOT AVAILABLE!!
603
//Cache pageChildCache = CacheFactory.getInstance().getCache (JahiaPageService.PAGE_CHILD_CACHE);
604
//if (pageChildCache == null)
605
// throw new JahiaException ("Internal Cache error", "Could not get the cache ["+
606
// JahiaPageService.PAGE_CHILD_CACHE +"] instance.",
607
// JahiaException.CACHE_ERROR, JahiaException.CRITICAL_SEVERITY);
608

609             int movedPageID = pageBean.getPageLinkID();
610             contentPage = ContentPage.getPage(movedPageID, true, true);
611
612             int oldParentFieldID = ServicesRegistry.getInstance().getJahiaPageService()
613                 .getPageFieldID(contentPage.getID());
614
615             // 0. Flush moved page cache to garantize to have the last staged.
616
ServicesRegistry.getInstance().getJahiaPageService().invalidatePageCache(movedPageID);
617
618             // 1. Relink the parent page to the new one, this also marks for
619
// deletion the parent field and container
620
contentPage.setParentID(pageBean.getParentID(), jParams);
621             contentPage.commitChanges(true);
622
623             // 2. Link the page ID to the new field
624
theField.setValue(Integer.toString(movedPageID));
625             // Set the object field
626
JahiaPage jahiaPage = contentPage.getPage(jParams);
627             theField.setObject(jahiaPage);
628             // Save the field modifications
629
theField.save(jParams);
630
631             // 3. Relink the parent ACL
632
contentPage.getACL().setParentID(theField.getAclID());
633
634             // 4. Invalidate all site maps.
635
ServicesRegistry.getInstance().getJahiaSiteMapService().resetSiteMap();
636
637             // 5. Flush page children cache.
638
//pageChildCache.remove (Integer.toString (pageBean.getParentID()));
639
//pageChildCache.remove (Integer.toString (oldParentPageID));
640

641             // 6. Delete or not the old parent container
642
if (pageBean.deleteOldContainer()){
643                 if (oldParentFieldID != -1) {
644                     // 1. Cut the page link in the parent field value
645
ContentPageField contentPageField = (ContentPageField)
646                         ContentPageField.getField(
647                         oldParentFieldID);
648                     // mark the parent container for deletion
649

650                     if (contentPageField != null) {
651                         try {
652                             ContentContainer parentContainer =
653                                 ContentContainer.getContainer(contentPageField.
654                                 getContainerID(), true);
655                             StateModificationContext stateModificationContext =
656                                 new StateModificationContext(parentContainer.
657                                 getObjectKey(), null, true);
658                             stateModificationContext.popAllLanguages();
659                             parentContainer.markLanguageForDeletion(jParams.
660                                 getUser(),
661                                 ContentObject.SHARED_LANGUAGE,
662                                 stateModificationContext);
663                         }
664                         catch (Throwable JavaDoc t) {
665                             logger.debug(
666                                 "Parent Container [" +
667                                 contentPageField.getContainerID()
668                                 + "] of page field[" + contentPageField.getID() +
669                                 "] not found");
670                         }
671                     }
672                 }
673             }
674
675         } else if (COPY_PAGE.equals(operation)) {
676             /** @todo To implement */
677         } else if (RESET_LINK.equals(operation)) {
678
679             if ( pageBean.getID()>-1 ){
680                 /* PAGE_MOVE_LOGIC we dont wan't to mark anything for delete with page move issue !!!!
681                 // 1. mark actual content for delete
682                 contentPage = ServicesRegistry.getInstance().getJahiaPageService().
683                                    lookupContentPage(pageBean.getID(), false);
684                 ContentPageField contentPageField =
685                     (ContentPageField)ContentPageField.getField(theField.getID());
686                 Map languageStates = contentPage.getLanguagesStates(false);
687                 Set languageCodes = languageStates.keySet();
688                 StateModificationContext stateModifContext =
689                     new StateModificationContext(new ContentFieldKey(theField.getID()),languageCodes);
690                 Iterator languageCodeIter = languageCodes.iterator();
691                 while (languageCodeIter.hasNext()) {
692                     String curLanguageCode = (String) languageCodeIter.next();
693                     contentPageField.markLanguageForDeletion(
694                         jParams.getUser(), curLanguageCode,
695                         stateModifContext);
696                 }*/

697                 // 2. set field page field value to -1.
698
ContentPageField contentPageField =
699                     (ContentPageField)ContentPageField.getField(theField.getID());
700                 contentPageField.setPageID(-1,jParams.getUser());
701             }
702
703             // Because the container and the associated field is always created
704
// before this sequence, they will be always deleted.
705
// Mark field and/or container for deletion to avoid having fake
706
// DB entries. Fake container entries are displayed in the parent container list.
707

708             /**
709              *
710             ContentPageField contentPageField = (ContentPageField)ContentPageField.getField(theField.getID());
711             boolean shouldDeleteFieldOnly = true;
712             int containerID = contentPageField.getContainerID();
713             if (containerID != 0) {
714                 JahiaContainer theContainer = ServicesRegistry.getInstance().getJahiaContainersService().
715                         loadContainer(containerID, LoadFlags.ALL, jParams);
716                 if (theContainer.getNbFields() == 1) { // Is it a one page field container ?
717                     // In this case it can be a fake container, remove it.
718                     ServicesRegistry.getInstance().getJahiaContainersService().
719                             deleteContainer(contentPageField.getContainerID(), jParams);
720                     shouldDeleteFieldOnly = false; // Field is deleted too.
721                 }
722             }
723             if (shouldDeleteFieldOnly && pageBean.getID() > -1) {
724                 contentPage = ServicesRegistry.getInstance().getJahiaPageService().
725                                    lookupContentPage(pageBean.getID(), false);
726                 Map languageStates = contentPage.getLanguagesStates(false);
727                 Set languageCodes = languageStates.keySet();
728                 StateModificationContext stateModifContext = new StateModificationContext(new ContentFieldKey(theField.getID()),languageCodes);
729                 Iterator languageCodeIter = languageCodes.iterator();
730                 while (languageCodeIter.hasNext()) {
731                     String curLanguageCode = (String) languageCodeIter.next();
732                     contentPageField.markLanguageForDeletion(
733                         jParams.getUser(), curLanguageCode,
734                         stateModifContext);
735                 }
736                 contentPageField.markLanguageForDeletion(
737                     jParams.getUser(), ContentObject.SHARED_LANGUAGE,
738                     stateModifContext);
739
740                 ServicesRegistry.getInstance().getJahiaPageService()
741                         .invalidatePageCache(contentPage.getID());
742             }
743             */

744
745             // FIXME NK :Why not ?
746
// contentPage = null; // Don't store title !
747
}
748         // Set Jahia page titles only if changed.
749
if (contentPage != null && (contentPage.hasActiveEntries()||contentPage.hasStagingEntries())) {
750             Enumeration JavaDoc titlesEnum = pageBean.getTitles().keys();
751             Hashtable JavaDoc contentPageTitles = contentPage.getTitles(true);
752             // Look for all page titles stored in the page bean and set the page
753
// that has changed.
754
boolean titleHasChanged = false;
755             while (titlesEnum.hasMoreElements()) {
756                 String JavaDoc languageCode = (String JavaDoc)titlesEnum.nextElement();
757                 String JavaDoc titleCandidate = pageBean.getTitle(languageCode);
758                 if (!titleCandidate.equals(contentPageTitles.get(languageCode))) {
759                     contentPage.setTitle(languageCode, titleCandidate, jParams.getEntryLoadRequest());
760                     titleHasChanged = true;
761                 }
762             }
763             contentPage.commitChanges(true);
764             if ( titleHasChanged ){
765                 ServicesRegistry.getInstance()
766                         .getJahiaSiteMapService().resetSiteMap();
767                 // index page title
768
int pageFieldID = ServicesRegistry.getInstance()
769                                 .getJahiaPageService().getPageFieldID(contentPage.getID());
770                 if (pageFieldID != -1) {
771                     ServicesRegistry.getInstance()
772                         .getJahiaSearchService().indexField(pageFieldID, true,
773                         jParams, true);
774                 }
775             }
776         }
777         return true;
778     }
779
780     /**
781      * Compose a Jahia temporary page for the field edition.
782      * Three cases should be considered :
783      * 1) The page already exists in the session (PageBean...) meaning that
784      * the page field is currently edited.
785      * 2) The page does not exist in the session and no object is set to the
786      * field meaning that a new page shoud be created. In this case, a temp page
787      * is created and set to the session.
788      * 3) The page does not exist in the session and an object (a page in fact)
789      * is already defined to the field object.
790      *
791      * @param jParams a ParamBean object
792      * @param engineMap the engine hashmap
793      * @param theField the field we are working on
794      * @return The temp page object
795      * @throws JahiaException
796      */

797     private JahiaPageEngineTempBean composePage(ParamBean jParams, HashMap JavaDoc engineMap, JahiaField theField)
798             throws JahiaException {
799
800         JahiaPageEngineTempBean pageBean = null;
801
802         HashMap JavaDoc pageBeans = (HashMap JavaDoc)jParams.
803                 getSession().getAttribute("Page_Field.PageBeans");
804         if ( pageBeans == null ){
805             pageBeans = new HashMap JavaDoc();
806             jParams.
807                 getSession().setAttribute("Page_Field.PageBeans", pageBeans);
808         }
809
810         // Verify if this page field was not already edited in this session.
811
pageBean = (JahiaPageEngineTempBean)pageBeans.get(theField.getDefinition().getName());
812
813         if (pageBean == null) {
814             // First call or recall of engine.
815
jParams.getSession().removeAttribute(SelectPage_Engine.SESSION_PARAMS);
816             if (theField.getObject() == null) {
817                 // Is it a new page ?
818

819                 // Is there a valid page ID in the field value ? If yes,
820
// this could mean we are denied access to the page.
821
int testPageID = -1;
822                 try {
823                     testPageID = Integer.parseInt(theField.getValue());
824                 } catch (NumberFormatException JavaDoc nfe) {
825                     testPageID = -1;
826                 }
827                 if (testPageID > 0) {
828                     ContentPage contentPage = null;
829                     try {
830                         contentPage = ContentPage.getPage(testPageID);
831                     } catch (JahiaException je) {
832                         
833                     }
834                     if (contentPage != null) {
835                         // if we reach this case, the page ID is valid,
836
// which means we are dealing with a page we do
837
// not have access to.
838
return null;
839                     }
840                 }
841                 logger.debug("New temp page... (theField.getObject() was null)");
842                 boolean isLinkOnly = theField.getValue().toLowerCase().indexOf("jahia_linkonly") != -1;
843                 pageBean = new JahiaPageEngineTempBean(
844                         -1, // Page ID
845
theField.getJahiaID(),
846                         theField.getPageID(),
847                         isLinkOnly ? JahiaPage.TYPE_URL : // URL type per default
848
JahiaPage.TYPE_DIRECT, // or create a new page per default
849
jParams.getSite().getDefaultTemplateID(), // Page default template
850
"http://", // URL undefined
851
-1, // Link ID undefined
852
jParams.getUser().getUserKey(),
853                         theField.getID()); // value should be < 0 if new field.
854
// pageBean.setOperation(isLinkOnly ? LINK_URL : CREATE_PAGE);
855
pageBean.setOperation(RESET_LINK);
856             } else {
857                 // We've got something in theField.object
858

859                 logger.debug("Get existing field page... (We've got something in theField.object())");
860                 JahiaPage jahiaPage = (JahiaPage)theField.getObject();
861
862                 ContentPage contentPage = null;
863                 try {
864                     contentPage = JahiaPageBaseService.getInstance().
865                         lookupContentPage(jahiaPage.getID(), jParams.getEntryLoadRequest(), true);
866                 } catch ( JahiaTemplateNotFoundException tnfe ){
867                     logger.debug("Template not foudn for page[" + jahiaPage.getID() +"], try return a ContentPage without template");
868                     contentPage = JahiaPageBaseService.getInstance().
869                         lookupContentPage(jahiaPage.getID(), jParams.getEntryLoadRequest(), false);
870                 }
871                 pageBean = new JahiaPageEngineTempBean(
872                         contentPage.getID(),
873                         contentPage.getJahiaID(),
874                         contentPage.getParentID(jParams.getEntryLoadRequest()),
875                         contentPage.getPageType(jParams.getEntryLoadRequest()),
876                         contentPage.getPageTemplateID(jParams),
877                         contentPage.getRemoteURL(jParams.getEntryLoadRequest()),
878                         contentPage.getPageLinkID(jParams.getEntryLoadRequest()),
879                         contentPage.getCreator(),
880                         theField.getID());
881                 if ( contentPage.getPageType(jParams.getEntryLoadRequest()) != -1 ){
882                     pageBean.setOperation(DEFAULT_OPERATION[contentPage.getPageType(jParams.getEntryLoadRequest())]);
883                 }
884                 pageBean.setTitles(contentPage.getTitles(ContentPage.LAST_UPDATED_TITLES));
885             }
886             pageBeans.put(theField.getDefinition().getName(), pageBean);
887         }
888         logger.debug(pageBean.toString());
889         return pageBean;
890     }
891
892     private static Logger logger = Logger.getLogger(Page_Field.class);
893 }
894
Popular Tags