KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > pages > JahiaPageBaseService


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  * 13-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
37  *
38  * ----- END LICENSE BLOCK -----
39  */

40
41 package org.jahia.services.pages;
42
43 import java.util.ArrayList JavaDoc;
44 import java.util.Enumeration JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Set JavaDoc;
50 import java.util.Vector JavaDoc;
51
52 import org.jahia.bin.Jahia;
53 import org.jahia.content.ContentObject;
54 import org.jahia.data.JahiaDOMObject;
55 import org.jahia.data.events.JahiaEvent;
56 import org.jahia.data.fields.JahiaField;
57 import org.jahia.data.fields.LoadFlags;
58 import org.jahia.data.files.JahiaFile;
59 import org.jahia.exceptions.JahiaException;
60 import org.jahia.exceptions.JahiaInitializationException;
61 import org.jahia.exceptions.JahiaOperationNotAllowedException;
62 import org.jahia.exceptions.JahiaPageNotFoundException;
63 import org.jahia.exceptions.JahiaTemplateNotFoundException;
64 import org.jahia.params.ParamBean;
65 import org.jahia.registries.ServicesRegistry;
66 import org.jahia.services.acl.ACLNotFoundException;
67 import org.jahia.services.acl.JahiaBaseACL;
68 import org.jahia.services.cache.Cache;
69 import org.jahia.services.cache.CacheFactory;
70 import org.jahia.services.fields.ContentField;
71 import org.jahia.services.sites.JahiaSite;
72 import org.jahia.services.usermanager.JahiaUser;
73 import org.jahia.services.version.ActivationTestResults;
74 import org.jahia.services.version.EntryLoadRequest;
75 import org.jahia.services.version.JahiaSaveVersion;
76 import org.jahia.services.version.StateModificationContext;
77 import org.jahia.settings.SettingsBean;
78
79 /**
80  * Class JahiaPageBaseService
81  *
82  * @author Eric Vassalli
83  * @author Khue
84  * @author Fulco Houkes
85  * @version 1.0
86  */

87 public class JahiaPageBaseService extends JahiaPageService {
88     private static org.apache.log4j.Logger logger =
89         org.apache.log4j.Logger.getLogger(JahiaPageBaseService.class);
90
91     private static final int VERSION_START_STATUS = 2;
92
93     /** the unique instance of this service */
94     private static JahiaPageBaseService instance;
95
96     private static int undefined_counter = 0;
97
98     // the Page Info cache name.
99
public static final String JavaDoc PAGE_INFO_CACHE = "PageInfoCache";
100     // the Page Versioning Info cache name.
101
public static final String JavaDoc VERSIONING_PAGE_INFO_CACHE = "VersioningPageInfoCache";
102     // the ContentPage cache name
103
public static final String JavaDoc CONTENT_PAGE_CACHE = "ContentPageCache";
104
105     /** The active Page info cache */
106     private static Cache mPageInfosCache;
107
108     /** The versioning info cache */
109     private static Cache mVersioningPageInfosCache;
110
111     /** the page child cache */
112     //private static Cache mPageChildIDsCache;
113

114     private Cache mContentPageCache;
115
116     private JahiaPagesDB mPageDB;
117     private JahiaPageUtilsDB mUtilsDB;
118     private JahiaPageTemplateService mTemplateService;
119
120     /**
121      * Default construtor, creates a new <code>JahiaPageBaseService</code> instance
122      *
123      * @throws JahiaException when an initilization exception occured
124      */

125     protected JahiaPageBaseService ()
126         throws JahiaException {
127     }
128
129     /**
130      * @param page
131      * @param loadFlag
132      * @param user
133      * @return
134      */

135     private boolean authorizePageLoad (JahiaPage page, int loadFlag,
136                                        JahiaUser user) {
137
138         if (!page.checkReadAccess(user)) {
139             return false;
140         }
141         if (loadFlag == PageLoadFlags.ALL) {
142             return true;
143         }
144         switch (page.getPageType()) {
145             case (JahiaPageInfo.TYPE_DIRECT):
146                 return loadFlag == PageLoadFlags.DIRECT;
147             case (JahiaPageInfo.TYPE_LINK):
148                 return loadFlag == PageLoadFlags.INTERNAL;
149             case (JahiaPageInfo.TYPE_URL):
150                 return loadFlag == PageLoadFlags.URL;
151         }
152         return false;
153     }
154
155     //-------------------------------------------------------------------------
156
public synchronized JahiaPage createPage (int siteID,
157                                               int parentID,
158                                               int pageType,
159                                               String JavaDoc title,
160                                               int pageTemplateID,
161                                               String JavaDoc remoteURL,
162                                               int pageLinkID,
163                                               String JavaDoc creator,
164                                               int parentAclID,
165                                               ParamBean jParam)
166         throws JahiaException {
167         // Check if the service is running
168
checkService();
169
170         logger.debug("Creating Page " + title + " ...");
171
172         // Verify if the specified parent page does exist
173
//
174
// khatmandu--------------
175
// MULTISITE ISSUE: if parent id equal zero, don't check parent page info...
176
//
177
if (parentID > 0) {
178             Vector JavaDoc parentPageInfoVector = lookupPageInfos(parentID,
179                 EntryLoadRequest.CURRENT);
180             if (parentPageInfoVector == null) {
181                 throw new JahiaException("Could not create page.",
182                                          "Could not create a new page : parent page [" +
183                                          parentID + "] not found.",
184                                          JahiaException.PAGE_ERROR,
185                                          JahiaException.ERROR_SEVERITY);
186             }
187             // FIXME (NK) : What is this ??????????
188
parentPageInfoVector = null;
189         }
190
191         // Get the next available counter.
192
/**
193          * rollback fix on JAHIA-240 because it causes migration problems.
194          */

195         //int pageID = ServicesRegistry.getInstance().getJahiaIncrementorsDBService().autoIncrement("jahia_pages_data");
196
int pageID = mPageDB.getNextID();
197
198         // No page hits until now ;)
199
int counter = 0;
200
201         // Get the current date.
202
String JavaDoc dateOfCreation = new Long JavaDoc( (new java.util.Date JavaDoc()).getTime()).
203                                 toString();
204
205         ContentPage linkedPage = null;
206         JahiaBaseACL acl = null;
207
208         // An new ACL is created and associated automaticaly to the new page
209
// only if the page is a DIRECT page or an URL link.
210
// In case of a LINK typed page, the ACL of the linked page will be
211
// used.
212
switch (pageType) {
213
214             case JahiaPage.TYPE_DIRECT:
215             case JahiaPage.TYPE_URL:
216
217                 // Create a new ACL for the page/URL.
218
acl = new JahiaBaseACL();
219                 if (acl != null) {
220                     try {
221                         acl.create(parentAclID);
222                     } catch (ACLNotFoundException ex) {
223                         throw new JahiaException("Could not create page.",
224                                                  "The parent ACL ID [" +
225                                                  parentAclID +
226                                                  "] could not be found," +
227                                                  " while trying to create a new page.",
228                                                  JahiaException.PAGE_ERROR,
229                                                  JahiaException.ERROR_SEVERITY);
230                     }
231                 } else {
232                     throw new JahiaException("Could not create page.",
233                                              "Could not instanciate a new ACL object while trying to create a new page.",
234                                              JahiaException.PAGE_ERROR,
235                                              JahiaException.CRITICAL_SEVERITY);
236                 }
237                 break;
238
239             case JahiaPage.TYPE_LINK:
240                 linkedPage =
241                     lookupContentPage(pageLinkID, jParam.getEntryLoadRequest(), true);
242                 //acl = linkedPage.getACL ();
243
acl = new JahiaBaseACL();
244                 if (acl != null) {
245                     try {
246                         acl.create(parentAclID);
247                     } catch (ACLNotFoundException ex) {
248                         throw new JahiaException("Could not create page.",
249                                                  "The parent ACL ID [" +
250                                                  parentAclID +
251                                                  "] could not be found," +
252                                                  " while trying to create a new page.",
253                                                  JahiaException.PAGE_ERROR,
254                                                  JahiaException.ERROR_SEVERITY);
255                     }
256                 } else {
257                     throw new JahiaException("Could not create page.",
258                                              "Could not instanciate a new ACL object while trying to create a new page.",
259                                              JahiaException.PAGE_ERROR,
260                                              JahiaException.CRITICAL_SEVERITY);
261                 }
262                 break;
263         }
264
265         JahiaPageDefinition pageTemplate = null;
266         switch (pageType) {
267             case JahiaPageInfo.TYPE_DIRECT:
268                 pageTemplate = mTemplateService.lookupPageTemplate(
269                     pageTemplateID);
270                 break;
271
272             case JahiaPageInfo.TYPE_LINK:
273                 pageTemplate = linkedPage.getPageTemplate(jParam);
274                 pageTemplateID = pageTemplate.getID();
275                 break;
276         }
277         linkedPage = null;
278
279         // checks if page title is not null
280
if ( (title == null) || ("".equals(title))) {
281             undefined_counter++;
282             title = "Undefined Page " + undefined_counter;
283         }
284
285         /**
286          * @todo FIXME we must test here if the page exists in other languages
287          * before attempting to create it all the time. For the moment we just
288          * added a boolean variable set to true but this value will have to
289          * be determined by trying to load the page before creating it.
290          */

291         boolean newPage = true;
292         ContentPage contentPage = null;
293         JahiaPage page = null;
294         if (newPage) {
295
296             JahiaSite site = ServicesRegistry.getInstance()
297                              .getJahiaSitesService().getSite(siteID);
298             /*
299                          int newVersionID = ServicesRegistry.getInstance()
300                              .getJahiaVersionService().getCurrentVersionID();
301              */

302             int newVersionID = 0; // Create a staging entry so the version ID should be 0
303

304             int newVersionStatus = VERSION_START_STATUS;
305             // At this point, the page definition exist and has been instanciate,
306
// as well as the ACL object could be created.
307
// Now create the raw page info object
308

309             String JavaDoc languageCode = null;
310             if (jParam != null) {
311                 languageCode = jParam.getEntryLoadRequest().getFirstLocale(true).
312                                toString();
313             } else {
314                 languageCode = site.getLanguageSettingsAsLocales(true).get(0).
315                                toString();
316             }
317
318             JahiaPageInfo pageInfo = new JahiaPageInfo(pageID, siteID, parentID,
319                 pageType, title, pageTemplateID, remoteURL, pageLinkID, creator,
320                 dateOfCreation, counter, acl.getID(), newVersionID,
321                 newVersionStatus,
322                 languageCode);
323             //jParam.getLocale().toString());
324
Vector JavaDoc pageInfoVector = new Vector JavaDoc();
325             pageInfoVector.add(pageInfo);
326             dateOfCreation = null;
327             if (pageInfo == null) {
328                 throw new JahiaException("Could not create page.",
329                                          "Could not instanciate a new JahiaPageInfo object.",
330                                          JahiaException.PAGE_ERROR,
331                                          JahiaException.CRITICAL_SEVERITY);
332             }
333
334             // insert the page info into the database.
335
if (!mPageDB.createPageInfo(pageInfo)) {
336                 throw new JahiaException("Could not create page.",
337                                          "Could not insert the page info into the database",
338                                          JahiaException.PAGE_ERROR,
339                                          JahiaException.CRITICAL_SEVERITY);
340             }
341
342             // Let's create the page!!
343
contentPage = new ContentPage(pageID, pageInfoVector, acl);
344             page =
345                 new JahiaPage(contentPage, pageTemplate, acl,
346                               jParam.getEntryLoadRequest());
347             acl = null;
348             if (page == null) {
349                 throw new JahiaException("Could not create page.",
350                                          "Could not instanciate a new JahiaPage object.",
351                                          JahiaException.PAGE_ERROR,
352                                          JahiaException.CRITICAL_SEVERITY);
353             }
354
355             // add the page into the cache
356
mPageInfosCache.put(new Integer JavaDoc(pageID), pageInfoVector);
357             pageInfo = null;
358         }
359         // Reset child cache for this parent page
360
//mPageChildIDsCache.remove(new Integer(parentID));
361
// log the page creation Event
362
JahiaEvent theEvent = new JahiaEvent(this, jParam, page);
363         ServicesRegistry.getInstance().getJahiaEventService().
364             fireAddPage(theEvent);
365         theEvent = null;
366
367         return page;
368     }
369
370     //-------------------------------------------------------------------------
371
// deletes all container lists in page
372
private void deleteAllPageContainerLists (JahiaPage thePage,
373                                               ParamBean jParams)
374         throws JahiaException {
375         ContentPage contentPage = lookupContentPage(
376             thePage.getID(), jParams.getEntryLoadRequest(), false);
377         Vector JavaDoc cListIDs = ServicesRegistry.getInstance()
378                           .getJahiaContainersService()
379                           .getContainerListIDsInPage(contentPage,
380             jParams.getEntryLoadRequest());
381         for (int i = 0; i < cListIDs.size(); i++) {
382             int cListID = ( (Integer JavaDoc) cListIDs.elementAt(i)).intValue();
383             logger.debug("Deleting container list ID " + cListID);
384             ServicesRegistry.getInstance().getJahiaContainersService().
385                 deleteContainerList(cListID, jParams);
386         }
387         cListIDs = null;
388     }
389
390     //-------------------------------------------------------------------------
391
// deletes all fields in page
392
private void deleteAllPageFields (JahiaPage thePage, ParamBean jParam)
393         throws JahiaException {
394         Vector JavaDoc fieldIDs = ServicesRegistry.getInstance().getJahiaFieldService().
395                           getNonContainerFieldIDsInPage(thePage.getID());
396         for (int i = 0; i < fieldIDs.size(); i++) {
397             int fieldID = ( (Integer JavaDoc) fieldIDs.elementAt(i)).intValue();
398             ServicesRegistry.getInstance().getJahiaFieldService().deleteField(
399                 fieldID,
400                 jParam);
401         }
402         fieldIDs = null;
403     }
404
405     //-------------------------------------------------------------------------
406
// deletes all fields/containers pointing on this page
407
private void deleteLinksOnPage (JahiaPage thePage, ParamBean jParam)
408         throws JahiaException {
409         Vector JavaDoc links = getPagesPointingOnPage(thePage.getID(), jParam);
410         for (int i = 0; i < links.size(); i++) {
411             JahiaPage theLink = (JahiaPage) links.elementAt(i);
412             int fieldID = mUtilsDB.getPageFieldID(theLink.getID());
413             if (fieldID != -1) {
414                 ServicesRegistry.getInstance().getJahiaFieldService().
415                     deleteField(fieldID,
416                                 jParam);
417             }
418         }
419         links = null;
420     }
421
422     //-------------------------------------------------------------------------
423
public synchronized void deletePage (JahiaPage theVictim, ParamBean jParam)
424         throws JahiaException, JahiaOperationNotAllowedException {
425         // Check if the service is running
426
checkService();
427
428         // Just be sure the victim did run away meanwhile ...
429
if (theVictim == null) {
430             return;
431         }
432
433         int currentPageID = -1;
434         if (jParam != null) {
435             currentPageID = jParam.getPageID();
436         }
437
438         // avoid to delete the current page ( except if we are in admin mode ).
439
if (jParam.isInAdminMode() || (theVictim.getID() != currentPageID)) {
440
441             // First remove it from the cache
442
mPageInfosCache.remove(new Integer JavaDoc(theVictim.getID()));
443             mVersioningPageInfosCache.remove(new Integer JavaDoc(theVictim.getID()));
444
445             // only direct pages do have content.
446
if (theVictim.getPageType() == JahiaPage.TYPE_DIRECT) {
447                 // delete all the fields associated to the page.
448
deleteAllPageFields(theVictim, jParam);
449
450                 // delete all the container list associated to the page.
451
deleteAllPageContainerLists(theVictim, jParam);
452
453                 // delete all links pointing on this page.
454
deleteLinksOnPage(theVictim, jParam);
455             }
456
457             // If the victim is a link, the ACL must not be deleted, because the
458
// page and the link share the same ACL object.
459
if (theVictim.getPageType() != JahiaPage.TYPE_LINK) {
460                 // delete the page's ACL
461
JahiaBaseACL acl = theVictim.getACL();
462                 acl.delete();
463                 acl = null;
464             }
465
466             // kill the files which belongs to the page
467
Vector JavaDoc files = ServicesRegistry.getInstance().
468                            getJahiaFilemanagerService().
469                            getFilesByPage(theVictim.getJahiaID(),
470                                           theVictim.getID(), false);
471             JahiaFile f = null;
472             for (int i = 0; i < files.size(); i++) {
473                 f = (JahiaFile) files.get(i);
474                 ServicesRegistry.getInstance().
475                        getJahiaFilemanagerService().
476                        deleteFileDB(f.getFileID());
477                 ServicesRegistry.getInstance().
478                        getJahiaFilemanagerService().
479                        deleteFile(f);
480             }
481
482             /** @todo this doesn't delete the versioned entries, should we do
483              * it or not ?
484              */

485
486             // now ... kill the victim !!
487
// let's retrieve all the entries, including the versioned ones.
488
Vector JavaDoc pageInfoVector = theVictim.getContentPage().getPageInfos(true);
489             Enumeration JavaDoc pageInfoEnum = pageInfoVector.elements();
490             while (pageInfoEnum.hasMoreElements()) {
491                 JahiaPageInfo curPageInfo = (JahiaPageInfo) pageInfoEnum.
492                                             nextElement();
493                 mPageDB.deletePageInfo(curPageInfo);
494             }
495
496             // be sure it's really dead !
497
theVictim = null;
498         } else {
499             throw new JahiaOperationNotAllowedException(theVictim.getID(),
500                 "It is not allowed to delete the current page. Delete it from its parent page.");
501         }
502
503     }
504
505     /**
506      * @param pageID
507      * @param levelNb
508      * @param jParams
509      * @return
510      * @throws JahiaException
511      */

512     public int findPageIDFromLevel (int pageID, int levelNb, ParamBean jParams)
513         throws JahiaException {
514         int levelCount = 0;
515         int parentID = -1;
516         ContentPage thePage = lookupContentPage(pageID, true);
517
518         if (levelNb != -1) {
519             while (levelCount < levelNb) {
520                 parentID = thePage.getParentID(jParams.getEntryLoadRequest());
521                 if (parentID > 0) {
522                     thePage =
523                         lookupContentPage(parentID, jParams.getEntryLoadRequest(), true);
524                 } else {
525                     return -1;
526                 }
527                 levelCount++;
528             }
529         } else {
530             while (parentID > 0) {
531                 parentID = thePage.getParentID(jParams.getEntryLoadRequest());
532                 if (parentID > 0) {
533                     thePage = lookupContentPage(parentID, true);
534                 }
535             }
536         }
537
538         return thePage.getID();
539     }
540
541     /**
542      * @param siteID
543      * @param loadFlag
544      * @param jParam
545      * @param user
546      * @return
547      * @throws JahiaException
548      */

549     public Enumeration JavaDoc getAllPages (int siteID, int loadFlag, ParamBean jParam,
550                                     JahiaUser user)
551         throws JahiaException {
552         // Check if the service is running
553
checkService();
554
555         Vector JavaDoc result = new Vector JavaDoc();
556
557         // the user must be non null
558
if (user != null) {
559
560             // get all the pages IDs in the specified site.
561
Vector JavaDoc allPages = getPageIDsInSite(siteID);
562
563             // for each page ID, lookup the page, and check if the page
564
// matches the load flags and if the user is authorized to see it.
565
for (int i = 0; i < allPages.size(); i++) {
566                 try {
567                     Integer JavaDoc id = (Integer JavaDoc) allPages.get(i);
568                     if (id.intValue() > 0) {
569                         JahiaPage page = lookupPage(id.intValue(),
570                             jParam.getEntryLoadRequest(),
571                             jParam.getOperationMode(),
572                             jParam.getUser(), false);
573
574                         if (page != null) {
575                             if (authorizePageLoad(page, loadFlag, user)) {
576                                 result.add(page);
577                             }
578                         }
579                     }
580                     id = null;
581                 } catch (JahiaPageNotFoundException ex) {
582                     // the page could not be found, ignore and don't add it
583
// into the resulting Vector.
584
} catch (JahiaTemplateNotFoundException ex) {
585                     // The page has an invalid page template, ignore and
586
// don't add it into the resulting Vector.
587
} catch (JahiaException ex) {
588                     // An error occured, just don't add the page into the
589
// resulting Vector.
590
}
591             }
592             allPages = null;
593         }
594         return result.elements();
595     }
596
597     /**
598      * Returns an instance of the page service class
599      *
600      * @return the unique instance of this class
601      */

602     public static synchronized JahiaPageBaseService getInstance ()
603         throws JahiaException {
604         if (instance == null) {
605             instance = new JahiaPageBaseService();
606         }
607         return instance;
608     }
609
610     /**
611      * Return a <code>Vector</code> of all the site IDs
612      *
613      * @return the vector of all the site IDs
614      * @throws JahiaException when a general failure occured
615      */

616     public Vector JavaDoc getAllSiteIDs ()
617         throws JahiaException {
618         // Check if the service is running
619
checkService();
620
621         Vector JavaDoc sites = new Vector JavaDoc();
622         sites.add(new Integer JavaDoc(1)); // big fuckin' fake :) .... as you said !!! (Fulco)
623
return sites;
624     }
625
626     /**
627      * @param siteID
628      * @return
629      * @throws JahiaException
630      */

631     public Vector JavaDoc getPageIDsInSite (int siteID)
632         throws JahiaException {
633         // Check if the service is running
634
checkService();
635
636         return mUtilsDB.getPageIDsInSite(siteID);
637     }
638
639     //-------------------------------------------------------------------------
640
public Vector JavaDoc getPageIDsInSite (int siteID, int linkType)
641         throws JahiaException {
642         // Check if the service is running
643
checkService();
644
645         return mUtilsDB.getPageIDsInSite(siteID, linkType);
646     }
647
648     //-------------------------------------------------------------------------
649
public Vector JavaDoc getPageIDsWithTemplate (int templateID)
650         throws JahiaException {
651         // Check if the service is running
652
checkService();
653
654         return mUtilsDB.getPageIDsWithTemplate(templateID);
655     }
656
657     //-------------------------------------------------------------------------
658
/**
659      * Returns the page field id that is parent of the given pageId.
660      * The order is by workflows state from most staged to active.
661      * Without marked for delete
662      *
663      * @param pageID int
664      * @throws JahiaException
665      * @return int
666      */

667     public int getPageFieldID (int pageID)
668         throws JahiaException {
669         checkService();
670         return mUtilsDB.getPageFieldID(pageID);
671     }
672
673     //-------------------------------------------------------------------------
674
/**
675      * Returns the active page field id that is parent of the given pageId.
676      *
677      * @param pageID int
678      * @throws JahiaException
679      * @return int
680      */

681     public int getActivePageFieldID (int pageID)
682             throws JahiaException {
683         checkService();
684         return mUtilsDB.getActivePageFieldID(pageID);
685     }
686
687     //-------------------------------------------------------------------------
688
/**
689      * Returns the staged page field id that is parent of the given pageId.
690      *
691      * @param pageID int
692      * @throws JahiaException
693      * @return int
694      */

695     public int getStagedPageFieldID (int pageID)
696             throws JahiaException {
697         checkService();
698         return mUtilsDB.getStagedPageFieldID(pageID);
699     }
700
701     /**
702      * Returns all the different field of type page IDs in staging mode in a given page.
703      *
704      * @param pageID the page for which to retrieve the field of type page
705      * @return always returns a Set object, but it might be empty. If non
706      * empty it contains Integer objects that represent the page IDs.
707      * @throws JahiaException
708      */

709     public Set JavaDoc getStagingPageFieldIDsInPage (int pageID)
710         throws JahiaException {
711         return mUtilsDB.getStagingPageFieldIDsInPage(pageID);
712     }
713
714     /**
715      * In case of a page move, a same page is pointed by both an active page field and a staged page field
716      * This method return a set of theses pages fields.
717      * The ids are sorted by workflows state ( most staged first )
718      *
719      * @param pageID int
720      * @return Vector
721      */

722     public Vector JavaDoc getStagingAndActivePageFieldIDs (int pageID)
723         throws JahiaException {
724         return mUtilsDB.getStagingAndActivePageFieldIDs(pageID);
725     }
726
727     //-------------------------------------------------------------------------
728
public Vector JavaDoc getPageChilds (int pageID, int loadFlag,
729                                  EntryLoadRequest loadRequest)
730         throws JahiaException {
731
732         // let's retrieve the guest user first...
733
ContentPage contentPage = lookupContentPage(pageID, true);
734         JahiaUser user = ServicesRegistry.getInstance().
735                               getJahiaUserManagerService()
736                               .lookupUser(contentPage.getJahiaID(), "guest");
737         ParamBean jParams = Jahia.getThreadParamBean();
738         if ( jParams != null ){
739             user = jParams.getUser();
740         }
741
742         return getPageChilds(pageID, loadFlag, user, loadRequest);
743     }
744
745     public Vector JavaDoc getPageChilds (int pageID, int loadFlag, ParamBean jParam)
746         throws JahiaException {
747
748         return getPageChilds(pageID, loadFlag, jParam.getUser(), jParam);
749     }
750
751     public Vector JavaDoc getPageChilds (int pageID, int loadFlag, JahiaUser user)
752         throws JahiaException {
753         // Suppose we have a site in French, using an arbitrary EntryLoadRequest.CURRENT doesn't work very well
754
// because it request page in English. So we prefer
755
ParamBean jParams = Jahia.getThreadParamBean();
756         EntryLoadRequest loadRequest = null;
757         if ( jParams != null ){
758             loadRequest = jParams.getEntryLoadRequest();
759         }
760         return getPageChilds(pageID, loadFlag, user,loadRequest);
761     }
762
763     public Vector JavaDoc getPageChilds (int pageID, int loadFlag, JahiaUser user,
764                                   EntryLoadRequest loadRequest)
765         throws JahiaException {
766
767         // Check if the service is running
768
checkService();
769
770         Vector JavaDoc childs = new Vector JavaDoc();
771
772         boolean directPageOnly = (( loadFlag & ( PageLoadFlags.ALL |
773                                                  PageLoadFlags.INTERNAL |
774                                                  PageLoadFlags.JAHIA |
775                                                  PageLoadFlags.LINKS |
776                                                  PageLoadFlags.URL ) )==0 );
777
778         Vector JavaDoc contentPageChilds =
779             getContentPageChilds(pageID,user,
780                                  (ContentPage.STAGING_PAGE_INFOS | ContentPage.ACTIVE_PAGE_INFOS),
781                                  ContentObject.SHARED_LANGUAGE,directPageOnly);
782
783         int size = contentPageChilds.size();
784         // For each child page ID, get the page reference.
785
for (int i = 0; i < size; i++) {
786             ContentPage contentPage = (ContentPage) contentPageChilds.get(i);
787
788             // try to get the page reference.
789
try {
790                 JahiaPage page = lookupPage(contentPage.getID(), loadRequest, user);
791                 // if the page exists add it to the child list if it matches
792
// the loading flag.
793
if ( (page != null) && (user != null)) {
794                     if (authorizePageLoad(page, loadFlag, user)) {
795                         childs.add(page);
796                     }
797                 }
798             } catch (JahiaPageNotFoundException ex) {
799                 // The page could not be found, don't add it into the resulting
800
// Vector.
801
} catch (JahiaTemplateNotFoundException ex) {
802                 // The page template could not be found, don't add it into the
803
// resulting Vector.
804
}
805         }
806
807         contentPageChilds = null;
808
809         // sort pages by IDs
810
sortPages(childs);
811         return childs;
812     }
813
814     private Vector JavaDoc getPageChilds (int pageID, int loadFlag, JahiaUser user,
815                                   ParamBean jParam)
816         throws JahiaException {
817         if (jParam != null) {
818             return getPageChilds(pageID, loadFlag, user,
819                                  jParam.getEntryLoadRequest());
820         } else {
821             logger.debug(
822                 "FIXME : Method called with null ParamBean, returning null... ");
823             return null;
824         }
825
826     }
827
828     /**
829      * Return an enumeration holding all the child PAGE(!) of the specified page.
830      * This method checks the rights for a user and loads only the pages a user
831      * is allowed to see.
832      *
833      * @param pageID The source page ID
834      * @param user A JahiaUser object for which to check the rights on the pages
835      * @param pageInfosFlag if Archived, return all
836      * @param languageCode if <code>null</code>, return all language
837      * @return a Vector of JahiaPage objects that are the childs of this page
838      * @throws JahiaException when problems while loading data from the persistent storage occured
839      */

840     public Vector JavaDoc getDirectContentPageChilds (int pageID, JahiaUser user,
841                                               int pageInfosFlag,
842                                               String JavaDoc languageCode)
843         throws JahiaException {
844         // Check if the service is running
845
checkService();
846         Vector JavaDoc childs = new Vector JavaDoc();
847         Vector JavaDoc childIDs = null;
848         //childIDs = (Vector) mPageChildIDsCache.get(intPageID);
849
//if (childIDs == null) {
850
// get all the child page IDs
851
childIDs = mUtilsDB.getPageChildIDs(pageID);
852             // FIXME : NO SUPPORT FOR VERSIONING
853
// mPageChildIDsCache.put(intPageID, childIDs);
854
//}
855

856         EntryLoadRequest loadRequest = null;
857         ArrayList JavaDoc langs = new ArrayList JavaDoc();
858         langs.add(
859             org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
860             ContentField.SHARED_LANGUAGE));
861         if (languageCode != null) {
862             langs.add(
863                 org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
864                 languageCode));
865         }
866         if ( (pageInfosFlag & ContentPage.STAGING_PAGE_INFOS) != 0) {
867             loadRequest =
868                 new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0,
869                                      langs);
870             loadRequest.setWithMarkedForDeletion(true);
871         } else if ( (pageInfosFlag & ContentPage.ACTIVE_PAGE_INFOS) != 0) {
872             loadRequest =
873                 new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0,
874                                      langs);
875             loadRequest.setWithMarkedForDeletion(true);
876         } else if ( (pageInfosFlag & ContentPage.ARCHIVED_PAGE_INFOS) != 0) {
877             loadRequest =
878                 new EntryLoadRequest(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
879                                      0, langs);
880             loadRequest.setWithDeleted(true);
881             loadRequest.setWithMarkedForDeletion(true);
882         }
883
884         EntryLoadRequest activeLoadRequest =
885             new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0,
886                                  langs);
887
888         // For each child page ID, get the page reference.
889
for (int i = 0; i < childIDs.size(); i++) {
890             Integer JavaDoc id = (Integer JavaDoc) childIDs.get(i);
891             // try to get the page reference.
892
try {
893                 ContentPage pageContent = ServicesRegistry.getInstance().
894                                           getJahiaPageService().
895                                           lookupContentPage(id.intValue(),
896                     loadRequest,
897                     false);
898                 if ( (pageContent != null) && (user != null)) {
899                     if (pageContent.getPageType(loadRequest) ==
900                         PageInfoInterface.TYPE_DIRECT &&
901                         pageContent.checkReadAccess(user)) {
902                         if (pageID != pageContent.getParentID(activeLoadRequest)) {
903                             continue;
904                         }
905                         if (pageInfosFlag == ContentPage.ARCHIVED_PAGE_INFOS) {
906                             childs.add(pageContent);
907                         } else {
908                             JahiaPageInfo pageInfo = null;
909                             if (languageCode != null &&
910                                 pageContent.hasEntries(pageInfosFlag,
911                                 languageCode)) {
912                                 pageInfo =
913                                     pageContent.getPageInfoVersion(loadRequest, false,
914                                     false);
915                             } else if (pageContent.hasEntries(pageInfosFlag)) {
916                                 pageInfo =
917                                     pageContent.getPageInfoVersion(loadRequest, false,
918                                     true);
919                             }
920                             if (pageInfo != null) {
921                                 childs.add(pageContent);
922                             }
923                         }
924                     }
925                 }
926             } catch (JahiaPageNotFoundException ex) {
927                 // The page could not be found, don't add it into the resulting
928
// Vector.
929
} catch (JahiaTemplateNotFoundException ex) {
930                 // The page template could not be found, don't add it into the
931
// resulting Vector.
932
}
933         }
934         childIDs = null;
935         return childs;
936     }
937
938     /**
939      * An implementation that support versioning !
940      *
941      * if pageInfosFlag is ContentPage.ACTIVE_PAGE_INFOS,
942      * returns active child pages only
943      *
944      * if pageInfosFlag is ContentPage.STAGING_PAGE_INFOS,
945      * returns staging and child pages ( returns pages that are marked for delete too )
946      *
947      * if pageInfosFlag is ContentPage.ARCHIVED_PAGE_INFOS,
948      * returns child pages ( returns pages that are active or deleted too )
949      *
950      * if pageInfosFlag is ContentPage.ACTIVE_PAGE_INFOS | ContentPage.STAGING_PAGE_INFOS,
951      * returns child pages ( returns pages that are active or deleted or only staged )
952      *
953      * if pageInfosFlag is ContentPage.ARCHIVED_PAGE_INFOS | ContentPage.STAGING_PAGE_INFOS,
954      * returns child pages ( returns pages that are active or deleted or only staged )
955      *
956      * Return an enumeration holding all the child PAGE(!) of the specified page.
957      * This method checks the rights for a user and loads only the pages a user
958      * is allowed to see.
959      *
960      * @param pageID the source page ID
961      * @param user a <code>JahiaUser</code> reference for which to check
962      * the rights on the
963      * pages
964      * @param pageInfosFlag if Archived, return all
965      * @param languageCode if <code>null</code>, return all language
966      * @param versionId used only if pageInfosFlag = ContentPage.ARCHIVED_PAGE_INFOS
967      * @param directPageOnly sould we return only direct page or not
968      * @return a Vector of JahiaPage objects that are the childs of this page
969      * @throws JahiaException thrown in the case we have problems while loading data from the persistent storage
970      */

971     public Vector JavaDoc getContentPageChilds (int pageID,
972                                         JahiaUser user,
973                                         int pageInfosFlag,
974                                         String JavaDoc languageCode,
975                                         int versionId,
976                                         boolean directPageOnly)
977         throws JahiaException {
978         // Check if the service is running
979
checkService();
980         Vector JavaDoc childs = new Vector JavaDoc();
981         Vector JavaDoc childIDs = new Vector JavaDoc();
982
983         if ( ((pageInfosFlag & ContentPage.STAGING_PAGE_INFOS) != 0)
984            && ((pageInfosFlag & ContentPage.ACTIVE_PAGE_INFOS) != 0) ) {
985             childIDs = mUtilsDB.getStagingPageChildIDs(pageID);
986             Vector JavaDoc activeChildIDs = mUtilsDB.getActivePageChildIDs(pageID);
987             // add the deleted childs too
988
int size = activeChildIDs.size();
989             Integer JavaDoc I = null;
990             for ( int i=0; i<size; i++ ){
991                 I = (Integer JavaDoc)activeChildIDs.get(i);
992                 if ( !childIDs.contains(I) ){
993                     int size2 = childIDs.size();
994                     Integer JavaDoc J = null;
995                     int pos = -1;
996                     boolean bigger = false;
997                     for ( int j=0; j<size2; j++ ){
998                         J = (Integer JavaDoc)childIDs.get(j);
999                         bigger = false;
1000                        if ( I.intValue() > J.intValue() ){
1001                            pos = j;
1002                            bigger = true;
1003                        }
1004                        if ( pos != -1 && !bigger ){
1005                            break;
1006                        }
1007                    }
1008                    if ( pos != -1 ){
1009                        childIDs.add(pos+1,I);
1010                    } else {
1011                        childIDs.add(0,I);
1012                    }
1013                }
1014            }
1015        } else if ( ((pageInfosFlag & ContentPage.ARCHIVED_PAGE_INFOS) != 0)
1016               && ((pageInfosFlag & ContentPage.STAGING_PAGE_INFOS) != 0) ) {
1017            childIDs = mUtilsDB.getVersioningPageChildIDs(pageID, versionId);
1018            Vector JavaDoc stagingChildIDs = mUtilsDB.getStagingPageChildIDs(pageID);
1019            // add the deleted childs too
1020
int size = stagingChildIDs.size();
1021            Integer JavaDoc I = null;
1022            for ( int i=0; i<size; i++ ){
1023                I = (Integer JavaDoc)stagingChildIDs.get(i);
1024                if ( !childIDs.contains(I) ){
1025                    int size2 = childIDs.size();
1026                    Integer JavaDoc J = null;
1027                    int pos = -1;
1028                    boolean bigger = false;
1029                    for ( int j=0; j<size2; j++ ){
1030                        J = (Integer JavaDoc)childIDs.get(j);
1031                        bigger = false;
1032                        if ( I.intValue() > J.intValue() ){
1033                            pos = j;
1034                            bigger = true;
1035                        }
1036                        if ( pos != -1 && !bigger ){
1037                            break;
1038                        }
1039                    }
1040                    if ( pos != -1 ){
1041                        childIDs.add(pos+1,I);
1042                    } else {
1043                        childIDs.add(0,I);
1044                    }
1045                }
1046            }
1047        } else if ( (pageInfosFlag & ContentPage.STAGING_PAGE_INFOS) != 0) {
1048            childIDs = mUtilsDB.getStagingPageChildIDs(pageID);
1049        } else if ( (pageInfosFlag & ContentPage.ACTIVE_PAGE_INFOS) != 0) {
1050            childIDs = mUtilsDB.getActivePageChildIDs(pageID);
1051        } else if ( (pageInfosFlag & ContentPage.ARCHIVED_PAGE_INFOS) != 0) {
1052            childIDs = mUtilsDB.getVersioningPageChildIDs(pageID,versionId);
1053        }
1054
1055        EntryLoadRequest loadRequest = null;
1056        ArrayList JavaDoc langs = new ArrayList JavaDoc();
1057        langs.add(
1058            org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
1059            ContentField.SHARED_LANGUAGE));
1060        if (languageCode != null) {
1061            langs.add(
1062                org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
1063                languageCode));
1064        }
1065        if ( (pageInfosFlag & ContentPage.STAGING_PAGE_INFOS) != 0) {
1066            loadRequest =
1067                new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0,
1068                                     langs);
1069            loadRequest.setWithMarkedForDeletion(true);
1070        } else if ( (pageInfosFlag & ContentPage.ACTIVE_PAGE_INFOS) != 0) {
1071            loadRequest =
1072                new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0,
1073                                     langs);
1074            loadRequest.setWithMarkedForDeletion(true);
1075        } else if ( (pageInfosFlag & ContentPage.ARCHIVED_PAGE_INFOS) != 0) {
1076            loadRequest =
1077                new EntryLoadRequest(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
1078                                     0, langs);
1079            loadRequest.setWithDeleted(true);
1080            loadRequest.setWithMarkedForDeletion(true);
1081        }
1082
1083/*
1084        ContentPage contentPage = null;
1085        while ( iterator.hasNext() ){
1086            contentPage = (ContentPage) iterator.next();
1087
1088            // check page move
1089            EntryLoadRequest loadRequest = new EntryLoadRequest(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
1090                                                versionId, EntryLoadRequest.VERSIONED.getLocales());
1091        int parentId = childPage.getParentID(loadRequest);
1092*/

1093
1094        // For each child page ID, get the page reference.
1095
for (int i = 0; i < childIDs.size(); i++) {
1096            Integer JavaDoc id = (Integer JavaDoc) childIDs.get(i);
1097            // try to get the page reference.
1098
try {
1099
1100                ContentPage pageContent = ContentPage.getPage(id.intValue());
1101
1102                // check if the page is currently moved
1103
if ( (pageInfosFlag == ContentPage.ACTIVE_PAGE_INFOS) ){
1104                    if ( pageID != pageContent.getParentID(loadRequest) ){
1105                        continue;
1106                    }
1107                }
1108
1109                if ( (pageContent != null) && (user != null)) {
1110                    if ( (!directPageOnly ||
1111                          (directPageOnly && pageContent.getPageType(
1112                        loadRequest) == PageInfoInterface.TYPE_DIRECT)) &&
1113                        pageContent.checkReadAccess(user)) {
1114                       childs.add(pageContent);
1115                    }
1116                }
1117            } catch (JahiaPageNotFoundException ex) {
1118                // The page could not be found, don't add it into the resulting
1119
// Vector.
1120
} catch (JahiaTemplateNotFoundException ex) {
1121                // The page template could not be found, don't add it into the
1122
// resulting Vector.
1123
}
1124        }
1125        childIDs = null;
1126        return childs;
1127    }
1128
1129    /**
1130     * Return an enumeration holding all the child PAGE(!) of the specified page.
1131     * This method checks the rights for a user and loads only the pages a user
1132     * is allowed to see.
1133     *
1134     * @param pageID the source page ID
1135     * @param user a <code>JahiaUser</code> reference for which to check
1136     * the rights on the
1137     * pages
1138     * @param pageInfosFlag if Archived, return all
1139     * @param languageCode if <code>null</code>, return all language
1140     * @param directPageOnly sould we return only direct page or not
1141     * @return a Vector of JahiaPage objects that are the childs of this page
1142     * @throws JahiaException thrown in the case we have problems while loading data from the persistent storage
1143     */

1144    public Vector JavaDoc getContentPageChilds (int pageID, JahiaUser user,
1145                                        int pageInfosFlag,
1146                                        String JavaDoc languageCode,
1147                                        boolean directPageOnly)
1148        throws JahiaException {
1149        // Check if the service is running
1150
checkService();
1151        Vector JavaDoc childs = new Vector JavaDoc();
1152        Vector JavaDoc childIDs = null;
1153        //childIDs = (Vector) mPageChildIDsCache.get(intPageID);
1154
//if (childIDs == null) {
1155
// get all the child page IDs
1156
childIDs = mUtilsDB.getPageChildIDs(pageID);
1157            // FIXME : NO SUPPORT FOR VERSIONING
1158
// mPageChildIDsCache.put(intPageID, childIDs);
1159
//}
1160

1161        EntryLoadRequest loadRequest = null;
1162        ArrayList JavaDoc langs = new ArrayList JavaDoc();
1163        langs.add(
1164            org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
1165            ContentField.SHARED_LANGUAGE));
1166        if (languageCode != null) {
1167            langs.add(
1168                org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
1169                languageCode));
1170        }
1171        if ( (pageInfosFlag & ContentPage.STAGING_PAGE_INFOS) != 0) {
1172            loadRequest =
1173                new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0,
1174                                     langs);
1175            loadRequest.setWithMarkedForDeletion(true);
1176        } else if ( (pageInfosFlag & ContentPage.ACTIVE_PAGE_INFOS) != 0) {
1177            loadRequest =
1178                new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0,
1179                                     langs);
1180            loadRequest.setWithMarkedForDeletion(true);
1181        } else if ( (pageInfosFlag & ContentPage.ARCHIVED_PAGE_INFOS) != 0) {
1182            loadRequest =
1183                new EntryLoadRequest(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
1184                                     0, langs);
1185            loadRequest.setWithDeleted(true);
1186            loadRequest.setWithMarkedForDeletion(true);
1187        }
1188
1189        // For each child page ID, get the page reference.
1190
for (int i = 0; i < childIDs.size(); i++) {
1191            Integer JavaDoc id = (Integer JavaDoc) childIDs.get(i);
1192            // try to get the page reference.
1193
try {
1194
1195                /*
1196                 ContentPage pageContent = ServicesRegistry.getInstance().
1197                 getJahiaPageService().lookupContentPage(id.intValue(), loadRequest, false);
1198                 */

1199                ContentPage pageContent = ContentPage.getPage(id.intValue());
1200
1201                // check if the page is currently moved
1202
if ( (pageInfosFlag == ContentPage.ACTIVE_PAGE_INFOS) ){
1203                    if ( pageID != pageContent.getParentID(loadRequest) ){
1204                        continue;
1205                    }
1206                }
1207
1208                if ( (pageContent != null) && (user != null)) {
1209                    if ( (!directPageOnly ||
1210                          (directPageOnly && pageContent.getPageType(
1211                        loadRequest) == PageInfoInterface.TYPE_DIRECT)) &&
1212                        pageContent.checkReadAccess(user)) {
1213                        if (pageInfosFlag == ContentPage.ARCHIVED_PAGE_INFOS) {
1214                            childs.add(pageContent);
1215                        } else {
1216                            JahiaPageInfo pageInfo = null;
1217                            if (languageCode != null &&
1218                                pageContent.hasEntries(pageInfosFlag,
1219                                languageCode)) {
1220                                pageInfo =
1221                                    pageContent.getPageInfoVersion(loadRequest, false,
1222                                    false);
1223                            } else if (pageContent.hasEntries(pageInfosFlag)) {
1224                                pageInfo =
1225                                    pageContent.getPageInfoVersion(loadRequest, false,
1226                                    true);
1227                            }
1228                            if (pageInfo != null) {
1229                                childs.add(pageContent);
1230                            }
1231                        }
1232                    }
1233                }
1234            } catch (JahiaPageNotFoundException ex) {
1235                // The page could not be found, don't add it into the resulting
1236
// Vector.
1237
} catch (JahiaTemplateNotFoundException ex) {
1238                // The page template could not be found, don't add it into the
1239
// resulting Vector.
1240
}
1241        }
1242        childIDs = null;
1243        return childs;
1244    }
1245
1246    /**
1247     * Should be used in place of getPagePath , use ContentPage instead of JahiaPage
1248     *
1249     * @param pageID
1250     * @param loadRequest
1251     * @param opMode
1252     * @param user
1253     * @return
1254     * @throws JahiaException
1255     */

1256    public Vector JavaDoc getContentPagePath (int pageID, EntryLoadRequest loadRequest,
1257                                      String JavaDoc opMode, JahiaUser user)
1258        throws JahiaException {
1259        // Check if the service is running
1260
checkService();
1261
1262        Vector JavaDoc path = new Vector JavaDoc();
1263        ContentPage contentPage = lookupContentPage (pageID, true);
1264        if (contentPage != null) {
1265            do {
1266                path.insertElementAt(contentPage, 0);
1267                // Coherence check here
1268
// if the loadRequest is active, but the page exist only in staging
1269
// ( for some reason, it was not actived ), so change the loadRequest to
1270
// staging ohterwhise calls to getType(), getJahiaID() will fail !!!!
1271
EntryLoadRequest newLoadRequest = loadRequest;
1272                if (loadRequest != null && loadRequest.isCurrent () && !contentPage.hasActiveEntries ()) {
1273                    newLoadRequest =
1274                            new EntryLoadRequest (EntryLoadRequest.STAGING_WORKFLOW_STATE,
1275                                    0, loadRequest.getLocales ());
1276                    newLoadRequest.setWithDeleted (loadRequest.isWithDeleted ());
1277                    newLoadRequest.setWithMarkedForDeletion (loadRequest.isWithMarkedForDeletion ());
1278                }
1279                int parentId = contentPage.getParentID(newLoadRequest);
1280                contentPage = parentId > 0 ? lookupContentPage (parentId, true) : null;
1281                  
1282                if (contentPage != null && contentPage.getID() == pageID) { // Check to avoid infinite loop when creating cyclic page move
1283
contentPage = null;
1284                }
1285            } while (contentPage != null);
1286        }
1287        return path;
1288    }
1289
1290    /**
1291     * Deprecated, use getContentPagePath
1292     *
1293     * @param pageID
1294     * @param loadRequest
1295     * @param opMode
1296     * @param user
1297     * @return
1298     * @throws JahiaException
1299     * @deprecated use getContentPagePath
1300     */

1301    public Vector JavaDoc getPagePath (int pageID, EntryLoadRequest loadRequest,
1302                               String JavaDoc opMode,
1303                               JahiaUser user)
1304        throws JahiaException {
1305        // Check if the service is running
1306
checkService();
1307
1308        Vector JavaDoc path = new Vector JavaDoc();
1309        JahiaPage thePage;
1310
1311        thePage = lookupPage(pageID, loadRequest, opMode, user, true);
1312        if (thePage != null) {
1313            path.add(thePage);
1314            while (thePage.getParentID() > 0) {
1315                thePage = lookupPage(thePage.getParentID(), loadRequest, opMode,
1316                                     user, true);
1317                if (thePage != null && thePage.getID() != pageID) { // Check to avoid infinite loop when creating cyclic page move
1318
path.insertElementAt(thePage, 0);
1319                } else {
1320                    return path;
1321                }
1322            }
1323        }
1324        thePage = null;
1325        return path;
1326    }
1327
1328    /**
1329     * Vector of contentPagePath
1330     *
1331     * @param pageID
1332     * @param jParams
1333     * @return
1334     * @throws JahiaException
1335     */

1336    public Vector JavaDoc getContentPagePath (int pageID, ParamBean jParams)
1337        throws JahiaException {
1338        if (jParams != null) {
1339            return getContentPagePath(pageID, jParams.getEntryLoadRequest(),
1340                                      jParams.getOperationMode(),
1341                                      jParams.getUser());
1342        } else {
1343            logger.debug(
1344                "FIXME : Method called with null ParamBean, returning null");
1345            return null;
1346        }
1347    }
1348
1349    /**
1350     * @param pageID
1351     * @param jParams
1352     * @return
1353     * @throws JahiaException
1354     * @deprecated used getContentPagePath
1355     */

1356    public Vector JavaDoc getPagePath (int pageID, ParamBean jParams)
1357        throws JahiaException {
1358        if (jParams != null) {
1359            return getPagePath(pageID, jParams.getEntryLoadRequest(),
1360                               jParams.getOperationMode(), jParams.getUser());
1361        } else {
1362            logger.debug(
1363                "FIXME : Method called with null ParamBean, returning null");
1364            return null;
1365        }
1366    }
1367
1368    public Vector JavaDoc getPagesPointingOnPage (int pageID, ParamBean jParam)
1369        throws JahiaException {
1370        return getPagesPointingOnPage(pageID, jParam.getEntryLoadRequest());
1371    }
1372
1373    public Vector JavaDoc getPagesPointingOnPage (int pageID,
1374                                          EntryLoadRequest loadRequest)
1375        throws JahiaException {
1376        // Check if the service is running
1377
checkService();
1378
1379        Vector JavaDoc pages = new Vector JavaDoc();
1380        Vector JavaDoc pageIDs = mUtilsDB.getPageIDsPointingOnPage(pageID, loadRequest);
1381
1382        for (int i = 0; i < pageIDs.size(); i++) {
1383            // get the page ID
1384
int pID = ( (Integer JavaDoc) pageIDs.elementAt(i)).intValue();
1385
1386            // get the page reference
1387
try {
1388                JahiaPage aPage = lookupPage(pID, loadRequest);
1389
1390                // if the page exists, add it to the vector
1391
if (aPage != null) {
1392                    if (aPage.getPageLinkID() != pageID) {
1393                        // this could happen if staging value and active
1394
// value differ.
1395
logger.debug("Page link " + pID + " no longer points to page " + pageID);
1396                    } else {
1397                        pages.add(aPage);
1398                    }
1399                }
1400                aPage = null;
1401            } catch (JahiaPageNotFoundException ex) {
1402                logger.debug("Not returning page " + pID +
1403                             " for referring pages, error:", ex);
1404            } catch (JahiaTemplateNotFoundException ex) {
1405                logger.debug("Not returning page " + pID +
1406                             " for referring pages, error:", ex);
1407            }
1408        }
1409
1410        pageIDs = null;
1411
1412        return pages;
1413    }
1414
1415    public Vector JavaDoc getPageSubTree (int pageID, int loadFlag, ParamBean jParam)
1416        throws JahiaException {
1417        // Check if the service is running
1418
checkService();
1419
1420        Vector JavaDoc subTree = getPageChilds(pageID, loadFlag, jParam);
1421        Vector JavaDoc results = new Vector JavaDoc(subTree);
1422        for (int i = 0; i < subTree.size(); i++) {
1423            JahiaPage aPage = (JahiaPage) subTree.elementAt(i);
1424            results.addAll(results.size(),getPageSubTree(aPage.getID(), loadFlag, jParam));
1425        }
1426
1427        return results;
1428    }
1429
1430    public synchronized void init (SettingsBean jSettings)
1431        throws JahiaInitializationException {
1432        logger.debug("** Initializing the Page Service ...");
1433        // do not allow initialization when the service is still running
1434
if (!isInitialized()) {
1435            // Initialize the pages cache
1436
logger.debug(" - Instanciate the page cache ...");
1437
1438            mPageInfosCache = CacheFactory.createCache(PAGE_INFO_CACHE);
1439
1440            mVersioningPageInfosCache = CacheFactory.createCache(
1441                VERSIONING_PAGE_INFO_CACHE);
1442
1443            //mPageChildIDsCache = CacheFactory.createCache(
1444
// PAGE_CHILD_CACHE);
1445

1446            mContentPageCache = CacheFactory.createCache(
1447                CONTENT_PAGE_CACHE);
1448
1449            // get the page DB access instance
1450
logger.debug(" - Instanciate the database page tools ...");
1451            mPageDB = JahiaPagesDB.getInstance();
1452
1453            // get the page utilities DB access instance
1454
logger.debug(" - Instanciate the database page utility tools ...");
1455            mUtilsDB = JahiaPageUtilsDB.getInstance();
1456
1457            // get the template service reference.
1458
logger.debug(" - Get the Page Template Service instance ...");
1459            ServicesRegistry services = ServicesRegistry.getInstance();
1460            if (services != null) {
1461                mTemplateService = services.getJahiaPageTemplateService();
1462            }
1463
1464            if ( (mPageInfosCache != null) &&
1465                (mVersioningPageInfosCache != null) &&
1466                (mPageDB != null) &&
1467                (mUtilsDB != null) &&
1468                (mTemplateService != null)) {
1469                mIsServiceInitialized = true;
1470                logger.debug(" ** Page Service successfully initialized!");
1471
1472                try {
1473                    // preloading page infos in cache
1474
mPageDB.preloadingPageInfos(mPageInfosCache,
1475                                                mVersioningPageInfosCache);
1476
1477                    ArrayList JavaDoc pageIDs = mUtilsDB.getFirstNPageIDs(jSettings.getPreloadCountForPageProperties());
1478                    PagePropertyDB.getInstance().preloadCacheByPageID(pageIDs);
1479                } catch (JahiaException je) {
1480                    throw new JahiaInitializationException("Error while preloading pages", je);
1481                }
1482
1483            } else {
1484                // invalidate the previous initializations
1485
mPageInfosCache = null;
1486                mVersioningPageInfosCache = null;
1487                mPageDB = null;
1488                mUtilsDB = null;
1489                mTemplateService = null;
1490
1491                // and raise an exception :(
1492
throw new JahiaInitializationException("Page Service initialization error.");
1493            }
1494        }
1495    }
1496
1497    public JahiaPage lookupPageWhitoutTemplates (int pageID)
1498        throws JahiaException,
1499        JahiaPageNotFoundException,
1500        JahiaTemplateNotFoundException {
1501        return lookupPage(pageID, EntryLoadRequest.CURRENT, false);
1502    }
1503
1504    /**
1505     * @param pageID
1506     * @return
1507     * @throws JahiaException
1508     * @throws JahiaPageNotFoundException
1509     * @throws JahiaTemplateNotFoundException
1510     */

1511    public JahiaPage lookupPage (int pageID)
1512        throws JahiaException,
1513        JahiaPageNotFoundException,
1514        JahiaTemplateNotFoundException {
1515        return lookupPage(pageID, EntryLoadRequest.CURRENT, true);
1516    }
1517
1518    //-------------------------------------------------------------------------
1519
/**
1520     * @param pageID
1521     * @param jParam
1522     * @return
1523     * @throws JahiaException
1524     * @throws JahiaPageNotFoundException
1525     * @throws JahiaTemplateNotFoundException
1526     */

1527    public JahiaPage lookupPage (int pageID, ParamBean jParam)
1528        throws JahiaException,
1529        JahiaPageNotFoundException,
1530        JahiaTemplateNotFoundException {
1531        return lookupPage(pageID, jParam, true);
1532    }
1533
1534    /**
1535     *
1536     * @param pageID int
1537     * @param loadRequest EntryLoadRequest
1538     * @param withTemplates boolean
1539     * @return JahiaPage
1540     * @throws JahiaException
1541     * @throws JahiaPageNotFoundException
1542     * @throws JahiaTemplateNotFoundException
1543     * @deprecated, use lookupPage (int pageID, EntryLoadRequest loadRequest,
1544                                 JahiaUser user, boolean withTemplates) instead, otherwize this is the site's default guest user that is used for permission access
1545     */

1546    public JahiaPage lookupPage (int pageID, EntryLoadRequest loadRequest,
1547                                 boolean withTemplates)
1548        throws JahiaException,
1549        JahiaPageNotFoundException,
1550        JahiaTemplateNotFoundException {
1551
1552        JahiaUser user = null;
1553        ParamBean jParams = Jahia.getThreadParamBean();
1554        if ( jParams != null ){
1555            user = jParams.getUser();
1556        }
1557        return lookupPage(pageID, loadRequest, user, withTemplates);
1558    }
1559
1560    /**
1561     *
1562     * @param pageID int
1563     * @param loadRequest EntryLoadRequest
1564     * @param user JahiaUser
1565     * @param withTemplates boolean
1566     * @return JahiaPage
1567     * @throws JahiaException
1568     * @throws JahiaPageNotFoundException
1569     * @throws JahiaTemplateNotFoundException
1570     */

1571    public JahiaPage lookupPage (int pageID, EntryLoadRequest loadRequest,
1572                                 JahiaUser user, boolean withTemplates)
1573        throws JahiaException,
1574        JahiaPageNotFoundException,
1575        JahiaTemplateNotFoundException {
1576        String JavaDoc operationMode = null;
1577        if (loadRequest.getWorkflowState() ==
1578            EntryLoadRequest.ACTIVE_WORKFLOW_STATE) {
1579            operationMode = ParamBean.NORMAL;
1580        }
1581        if ( (loadRequest.getWorkflowState() >
1582              EntryLoadRequest.ACTIVE_WORKFLOW_STATE)
1583             || (loadRequest.getWorkflowState() < EntryLoadRequest.VERSIONED_WORKFLOW_STATE) ) {
1584            operationMode = ParamBean.EDIT;
1585        }
1586        return lookupPage(pageID, loadRequest, operationMode, user,
1587                          withTemplates);
1588    }
1589
1590    /**
1591     *
1592     * @param pageID int
1593     * @param loadRequest EntryLoadRequest
1594     * @return JahiaPage
1595     * @throws JahiaException
1596     * @throws JahiaPageNotFoundException
1597     * @throws JahiaTemplateNotFoundException
1598     * @deprecated, use lookupPage (int pageID, EntryLoadRequest loadRequest, JahiaUser user) instead, otherwize this is the site's default guest user that is used for permission access
1599     */

1600    public JahiaPage lookupPage (int pageID, EntryLoadRequest loadRequest)
1601        throws JahiaException,
1602        JahiaPageNotFoundException,
1603        JahiaTemplateNotFoundException {
1604        return lookupPage(pageID, loadRequest, true);
1605    }
1606
1607    /**
1608     *
1609     * @param pageID int
1610     * @param loadRequest EntryLoadRequest
1611     * @param user JahiaUser
1612     * @return JahiaPage
1613     * @throws JahiaException
1614     * @throws JahiaPageNotFoundException
1615     * @throws JahiaTemplateNotFoundException
1616     */

1617    public JahiaPage lookupPage (int pageID,
1618                                 EntryLoadRequest loadRequest,
1619                                 JahiaUser user)
1620        throws JahiaException,
1621        JahiaPageNotFoundException,
1622        JahiaTemplateNotFoundException {
1623        return lookupPage(pageID, loadRequest, user, true);
1624    }
1625
1626    /**
1627     * Retrieves the page content object, that represents all the page versions
1628     * both active and staging. This object also contains all the multiple
1629     * language version of a page.
1630     *
1631     * @param pageID the identifier of the page to load.
1632     * @param withTemplates specifies whether page templates should be also
1633     * loaded or not.
1634     * @return a ContentPage object.
1635     * @throws JahiaException
1636     * @throws JahiaPageNotFoundException
1637     * @throws JahiaTemplateNotFoundException
1638     */

1639    public ContentPage lookupContentPage (int pageID,
1640                                          boolean withTemplates)
1641        throws JahiaException,
1642        JahiaPageNotFoundException,
1643        JahiaTemplateNotFoundException {
1644        return lookupContentPage(pageID, EntryLoadRequest.CURRENT,
1645                                 withTemplates, false);
1646    }
1647
1648    /**
1649     * Retrieves the page content object, that represents all the page versions
1650     * both active and staging. This object also contains all the multiple
1651     * language version of a page.
1652     *
1653     * @param pageID the identifier of the page to load.
1654     * @param withTemplates specifies whether page templates should be also
1655     * loaded or not.
1656     * @param forceLoadFromDB false if page can be read from cache
1657     * @return a ContentPage object.
1658     * @throws JahiaException
1659     * @throws JahiaPageNotFoundException
1660     * @throws JahiaTemplateNotFoundException
1661     */

1662    public ContentPage lookupContentPage (int pageID,
1663                                          boolean withTemplates,
1664                                          boolean forceLoadFromDB)
1665        throws JahiaException,
1666        JahiaPageNotFoundException,
1667        JahiaTemplateNotFoundException {
1668        return lookupContentPage(pageID, EntryLoadRequest.CURRENT,
1669                                 withTemplates, forceLoadFromDB);
1670    }
1671    
1672    
1673    /**
1674     * Retrieves the page content object, that represents all the page versions
1675     * both active and staging. This object also contains all the multiple
1676     * language version of a page.
1677     *
1678     * @param pageID the identifier of the page to load.
1679     * @param loadRequest specifies the EntryLoadRequest to specify which
1680     * contains the entry to be loaded, such as deleted, versioned (with
1681     * version ID, etc...)
1682     * @param withTemplates specifies whether page templates should be also
1683     * loaded or not.
1684     * @return a ContentPage object.
1685     * @throws JahiaException
1686     * @throws JahiaPageNotFoundException
1687     * @throws JahiaTemplateNotFoundException
1688     */

1689    public ContentPage lookupContentPage (int pageID,
1690                                          EntryLoadRequest loadRequest,
1691                                          boolean withTemplates)
1692        throws JahiaException,
1693        JahiaPageNotFoundException,
1694        JahiaTemplateNotFoundException {
1695        return lookupContentPage(pageID, loadRequest,
1696                withTemplates, false);
1697    }
1698        
1699    /**
1700     * Retrieves the page content object, that represents all the page versions
1701     * both active and staging. This object also contains all the multiple
1702     * language version of a page.
1703     *
1704     * @param pageID the identifier of the page to load.
1705     * @param loadRequest specifies the EntryLoadRequest to specify which
1706     * contains the entry to be loaded, such as deleted, versioned (with
1707     * version ID, etc...)
1708     * @param withTemplates specifies whether page templates should be also
1709     * loaded or not.
1710     * @param forceLoadFromDB false if page can be read from cache
1711     * @return a ContentPage object.
1712     * @throws JahiaException
1713     * @throws JahiaPageNotFoundException
1714     * @throws JahiaTemplateNotFoundException
1715     */

1716    public ContentPage lookupContentPage (int pageID,
1717                                          EntryLoadRequest loadRequest,
1718                                          boolean withTemplates,
1719                                          boolean forceLoadFromDB)
1720        throws JahiaException,
1721        JahiaPageNotFoundException,
1722        JahiaTemplateNotFoundException {
1723        //logger.debug(" lookup page id=" + pageID );
1724
ContentPage contentPage = null;
1725        
1726        // Check if the service is running
1727
checkService();
1728        if (!forceLoadFromDB) {
1729            contentPage = (ContentPage) mContentPageCache.get(new
1730                  Integer JavaDoc(pageID));
1731            if (contentPage != null) {
1732                return contentPage;
1733            }
1734        }
1735
1736        // Get the raw page infos
1737
Vector JavaDoc activePageInfoVector = lookupPageInfos(pageID,
1738            EntryLoadRequest.CURRENT);
1739        Vector JavaDoc archivePageInfoVector = lookupPageInfos(pageID,
1740            EntryLoadRequest.VERSIONED);
1741        if (archivePageInfoVector == null) {
1742            archivePageInfoVector = new Vector JavaDoc();
1743        }
1744
1745        if (activePageInfoVector == null) {
1746            throw new JahiaPageNotFoundException(pageID);
1747        }
1748
1749        if (activePageInfoVector.size() == 0 &&
1750            archivePageInfoVector.size() == 0) {
1751            throw new JahiaPageNotFoundException(pageID);
1752        }
1753
1754        Vector JavaDoc pageInfoVector = new Vector JavaDoc();
1755        pageInfoVector.addAll(activePageInfoVector);
1756        pageInfoVector.addAll(archivePageInfoVector);
1757
1758        JahiaPageInfo sharedPageInfo = (JahiaPageInfo) pageInfoVector.elementAt(
1759            0);
1760
1761        //////////////////////////////////////////////////////////////////////////////////////
1762
// FIXME -Fulco-
1763
//
1764
// this check should be removed the day we decide to make of links real objects and
1765
// not a special case of a page.
1766
//
1767
//////////////////////////////////////////////////////////////////////////////////////
1768

1769        // If the page is of DIRECT type, try to get the page Template
1770
// reference. If the page is not of this type, the page template
1771
// is not needed and so the page template reference will be set to null.
1772
if (withTemplates) { // AK. only if templates are requested.
1773
if ( (sharedPageInfo.getPageType() == JahiaPageInfo.TYPE_DIRECT) ||
1774                (sharedPageInfo.getPageType() == JahiaPageInfo.TYPE_LINK)) {
1775                mTemplateService.lookupPageTemplate(
1776                    sharedPageInfo.getPageTemplateID());
1777            }
1778        }
1779
1780        // Get the ACL object associated to the page, if the ACL is not found,
1781
// report the error.
1782
JahiaBaseACL acl = new JahiaBaseACL(sharedPageInfo.getAclID());
1783        if (acl == null) {
1784            throw new JahiaException("Page ACL not found.",
1785                                     "The ACL [" + sharedPageInfo.getAclID() +
1786                                     "] could not be found in the" +
1787                                     " database for page [" + pageID + "]",
1788                                     JahiaException.PAGE_ERROR,
1789                                     JahiaException.ERROR_SEVERITY);
1790        }
1791
1792        // Looks like everything is going well, let's create the page facade !
1793
contentPage = new ContentPage(pageID, pageInfoVector, acl);
1794        mContentPageCache.put(new Integer JavaDoc(pageID), contentPage);
1795        return contentPage;
1796    }
1797
1798    //-------------------------------------------------------------------------
1799
// AK 03.05.2001 lookup page whitout checks on templates... by passing new boolean (false).
1800
public JahiaPage lookupPage (int pageID, EntryLoadRequest loadRequest,
1801                                 String JavaDoc operationMode, JahiaUser user,
1802                                 boolean withTemplates)
1803        throws JahiaException,
1804        JahiaPageNotFoundException,
1805        JahiaTemplateNotFoundException {
1806
1807        ContentPage contentPage = lookupContentPage(pageID, withTemplates);
1808        //JahiaPage page = new JahiaPage (contentPage, contentPage.getPageTemplate(jParam), contentPage.getACL(), jParam);
1809
JahiaPage page = null;
1810        if (contentPage != null) {
1811            page = contentPage.getPage(loadRequest, operationMode, user);
1812        }
1813
1814        return page;
1815    }
1816
1817    public JahiaPage lookupPage (int pageID, ParamBean jParam,
1818                                 boolean withTemplates)
1819        throws JahiaException,
1820        JahiaPageNotFoundException,
1821        JahiaTemplateNotFoundException {
1822        if (jParam != null) {
1823            return lookupPage(pageID, jParam.getEntryLoadRequest(),
1824                              jParam.getOperationMode(), jParam.getUser(),
1825                              withTemplates);
1826        } else {
1827            logger.debug(
1828                "FIXME : Method called with null ParamBean, returning null");
1829            return null;
1830        }
1831    }
1832
1833    //-------------------------------------------------------------------------
1834
// Return the Vector of the requested page infos. First try to extract
1835
// the info out of the cache, if not present extract if from the
1836
// database, and add it to the cache.
1837
// Return null if the page info doesn't exist.
1838
private Vector JavaDoc lookupPageInfos (int pageID, EntryLoadRequest loadRequest)
1839        throws JahiaException {
1840        // Get the raw page infos
1841
Vector JavaDoc pageInfoVector = null;
1842        boolean versioning = ! (loadRequest.getWorkflowState() >=
1843                                EntryLoadRequest.ACTIVE_WORKFLOW_STATE);
1844        if (!versioning) {
1845            pageInfoVector = (Vector JavaDoc) mPageInfosCache.get(new Integer JavaDoc(pageID));
1846        } else {
1847            pageInfoVector = (Vector JavaDoc) mVersioningPageInfosCache.get(new Integer JavaDoc(
1848                pageID));
1849        }
1850        if (pageInfoVector == null) {
1851            // the page doesn't exist yet in the cache, load it from the
1852
// database.
1853
pageInfoVector = mPageDB.loadPageInfos(pageID, loadRequest);
1854            if (pageInfoVector == null) {
1855                pageInfoVector = new Vector JavaDoc();
1856            }
1857            if (!versioning) {
1858                mPageInfosCache.put(new Integer JavaDoc(pageID), pageInfoVector);
1859            } else {
1860                mVersioningPageInfosCache.put(new Integer JavaDoc(pageID),
1861                                              pageInfoVector);
1862            }
1863        }
1864        return pageInfoVector;
1865    }
1866
1867    //-------------------------------------------------------------------------
1868
public synchronized void shutdown () {
1869        //////////////////////////////////////////////////////////////////////////////////////
1870
// FIXME -Fulco- :
1871
// before shutting down the service, a check should be done to know
1872
// if a page has an update-lock active. If any active update-lock is
1873
// active, the system can not be shutdown !
1874
// If the shutdown process can be forced, a message should indicate the editing
1875
// user the service is in shutdown process, as soon as he does an action.
1876
//////////////////////////////////////////////////////////////////////////////////////
1877

1878        if (isInitialized()) {
1879            mPageInfosCache.flush();
1880            mVersioningPageInfosCache.flush();
1881            //mPageChildIDsCache.flush();
1882
mIsServiceInitialized = false;
1883        }
1884    }
1885
1886    //-------------------------------------------------------------------------
1887
// Sorts pages by ID
1888
private void sortPages (Vector JavaDoc pagesList) {
1889        JahiaPage pageA;
1890        JahiaPage pageB;
1891
1892        for (int i = 0; i < pagesList.size(); i++) {
1893            for (int j = i; j < pagesList.size(); j++) {
1894                pageA = (JahiaPage) pagesList.elementAt(i);
1895                pageB = (JahiaPage) pagesList.elementAt(j);
1896                if (pageA.getID() > pageB.getID()) {
1897                    pagesList.setElementAt(pageB, i);
1898                    pagesList.setElementAt(pageA, j);
1899                }
1900            }
1901        }
1902        pageA = null;
1903        pageB = null;
1904    }
1905
1906    //-------------------------------------------------------------------------
1907
/**
1908     * return a copy (clone) of the jahia page.
1909     * all the page content and the acl are cloned too.
1910     *
1911     * @param newParentID int parentID of the cloned page
1912     * if -1, newParentID = parentID of the page to clone.
1913     * @param newParentAclID int the id of the parent of the acl.
1914     * if -1, newParentAclID = parentAclID of the acl to clone.
1915     * @param pageToClone JahiaPage the page to clone.
1916     * @param childrenCloned true if the direct links to children pages are to
1917     * be preserved in the copy, false otherwise
1918     * @return return a JahiaPage which is the clone of the page in parameter.
1919     */

1920    public synchronized JahiaPage clonePage (int newParentID,
1921                                             int newParentAclID,
1922                                             JahiaPage pageToClone,
1923                                             ParamBean jParam,
1924                                             boolean childrenCloned)
1925        throws JahiaException {
1926        if (pageToClone == null) {
1927            return null;
1928        }
1929
1930        // Check if the service is running
1931
checkService();
1932        ServicesRegistry sReg = ServicesRegistry.getInstance();
1933
1934        // Verify the page to clone exist
1935
int pageToCloneID = pageToClone.getID();
1936        Vector JavaDoc pageToCloneInfoVector = pageToClone.getContentPage().
1937                                       getPageInfos(true);
1938        if (pageToCloneInfoVector == null) {
1939            throw new JahiaException("Could not clone page.",
1940                                     "Could not clone the page : page [" +
1941                                     pageToCloneID + "] not found.",
1942                                     JahiaException.PAGE_ERROR,
1943                                     JahiaException.ERROR_SEVERITY);
1944        }
1945
1946        // Get the next available counter.
1947
/**
1948         * rollback fix on JAHIA-240 because it causes migration problems.
1949         */

1950        // int pageID = ServicesRegistry.getInstance().getJahiaIncrementorsDBService().autoIncrement("jahia_pages_data");
1951
int pageID = mPageDB.getNextID();
1952
1953        // Get the current date.
1954
String JavaDoc dateOfCreation = new Long JavaDoc( (new java.util.Date JavaDoc()).getTime()).
1955                                toString();
1956
1957        // clone the page's ACL
1958
JahiaBaseACL aclToClone = pageToClone.getACL();
1959        if (aclToClone == null) {
1960            throw new JahiaException("Could not clone page.",
1961                                     "Could not get JahiaBaseACL object.",
1962                                     JahiaException.PAGE_ERROR,
1963                                     JahiaException.CRITICAL_SEVERITY);
1964        }
1965        JahiaBaseACL clonedACL = null;
1966
1967        clonedACL = (JahiaBaseACL) aclToClone.clone();
1968        if (clonedACL == null) {
1969            throw new JahiaException("Could not clone page.",
1970                                     "Could not clone acl.",
1971                                     JahiaException.PAGE_ERROR,
1972                                     JahiaException.CRITICAL_SEVERITY);
1973        }
1974
1975        if (newParentAclID != -1) {
1976            clonedACL.setParentID(newParentAclID);
1977        }
1978        int pageAclID = clonedACL.getID();
1979
1980        // get the template
1981
JahiaPageDefinition pageTemplate = pageToClone.getPageTemplate();
1982
1983        Enumeration JavaDoc pageInfoEnum = pageToCloneInfoVector.elements();
1984        Vector JavaDoc pageInfoVector = new Vector JavaDoc();
1985        while (pageInfoEnum.hasMoreElements()) {
1986
1987            JahiaPageInfo pageToCloneInfo = (JahiaPageInfo) pageInfoEnum.
1988                                            nextElement();
1989
1990            // clone the JahiaPageInfo
1991
JahiaPageInfo pageInfo = pageToCloneInfo.clonePageInfo(clonedACL.
1992                getID(),
1993                newParentID, pageID, dateOfCreation);
1994            if (pageInfo == null) {
1995                throw new JahiaException("Could not clone page.",
1996                                         "Could not clone JahiaPageInfo object.",
1997                                         JahiaException.PAGE_ERROR,
1998                                         JahiaException.CRITICAL_SEVERITY);
1999            }
2000
2001            pageInfoVector.add(pageInfo);
2002
2003            // insert the page info into the database.
2004
if (!mPageDB.createPageInfo(pageInfo)) {
2005                throw new JahiaException("Could not clone page.",
2006                                         "Could not insert the page info into the database",
2007                                         JahiaException.PAGE_ERROR,
2008                                         JahiaException.CRITICAL_SEVERITY);
2009            }
2010        }
2011
2012        // Let's create the page!!
2013
ContentPage contentPage = new ContentPage(pageID, pageInfoVector,
2014                                                  clonedACL);
2015        JahiaPage page = new JahiaPage(contentPage, pageTemplate, clonedACL,
2016                                       jParam.getEntryLoadRequest());
2017        if (page == null) {
2018            throw new JahiaException("Could not clone page.",
2019                                     "Could not instanciate a new JahiaPage object.",
2020                                     JahiaException.PAGE_ERROR,
2021                                     JahiaException.CRITICAL_SEVERITY);
2022        }
2023
2024        // add the page into the cache
2025
mPageInfosCache.put(new Integer JavaDoc(pageID), pageInfoVector);
2026
2027        // log the page creation Event
2028
JahiaEvent theEvent = new JahiaEvent(this, jParam, page);
2029        sReg.getJahiaEventService().
2030            fireAddPage(theEvent);
2031
2032        // clone all container list in page
2033
ContentPage contentPageToClone = lookupContentPage(pageToClone.getID(),
2034            jParam.getEntryLoadRequest(), true);
2035        Vector JavaDoc cListIDs = sReg.getJahiaContainersService(
2036            ).getContainerListIDsInPage(contentPageToClone,
2037                                        jParam.getEntryLoadRequest());
2038
2039        int cListID;
2040        for (int i = 0; i < cListIDs.size(); i++) {
2041            cListID = ( (Integer JavaDoc) cListIDs.elementAt(i)).intValue();
2042
2043            sReg.getJahiaContainersService().cloneContainerList(cListID, pageID,
2044                pageAclID,
2045                childrenCloned);
2046
2047        }
2048
2049        // clone all fields in page
2050
Vector JavaDoc fieldIDs = sReg.getJahiaFieldService().
2051                          getNonContainerFieldIDsInPageByWorkflowState(
2052            pageToClone.getID(),
2053            EntryLoadRequest.CURRENT);
2054
2055        int fieldID;
2056        JahiaField field;
2057
2058        for (int i = 0; i < fieldIDs.size(); i++) {
2059            // @toto : clone field inn multi-language
2060
fieldID = ( (Integer JavaDoc) fieldIDs.elementAt(i)).intValue();
2061            field =
2062                sReg.getJahiaFieldService().loadField(fieldID,
2063                LoadFlags.NOTHING, jParam);
2064            sReg.getJahiaFieldService().cloneField(field, 0, pageID, pageAclID,
2065                childrenCloned);
2066        }
2067
2068        return page;
2069    }
2070
2071    //-------------------------------------------------------------------------
2072
// FH 2 May 2001
2073
// javadocs automaticaly imported.
2074
//
2075
public int getNbPages ()
2076        throws JahiaException {
2077        return mUtilsDB.getNbPages();
2078    }
2079
2080    //-------------------------------------------------------------------------
2081
// FH 2 May 2001
2082
// javadocs automaticaly imported.
2083
//
2084
public int getNbPages (int siteID)
2085        throws JahiaException {
2086        return mUtilsDB.getNbPages(siteID);
2087    }
2088
2089    //-------------------------------------------------------------------------
2090
// FH 2 May 2001
2091
// javadocs automaticaly imported.
2092
//
2093
public int getRealActiveNbPages ()
2094        throws JahiaException {
2095        return mUtilsDB.getRealActiveNbPages();
2096    }
2097
2098    //-------------------------------------------------------------------------
2099
// FH 2 May 2001
2100
// javadocs automaticaly imported.
2101
//
2102
public int getRealActiveNbPages (int siteID)
2103        throws JahiaException {
2104        return mUtilsDB.getRealActiveNbPages(siteID);
2105    }
2106
2107    // NK
2108
/**
2109     * returns a DOM representation of all pages of a site
2110     *
2111     * @param siteID
2112     */

2113    public JahiaDOMObject getPagesAsDOM (int siteID)
2114        throws JahiaException {
2115
2116        return JahiaPageUtilsDB.getInstance().getPagesAsDOM(siteID);
2117
2118    }
2119
2120    // NK
2121
/**
2122     * Returns a vector of all pages' Acl ID of this site
2123     * Need this for site extraction
2124     *
2125     * @param siteID
2126     */

2127    public Vector JavaDoc getAclIDs (int siteID)
2128        throws JahiaException {
2129        return mUtilsDB.db_get_all_acl_id(siteID);
2130    }
2131
2132    public void invalidatePageCache (int pageID) {
2133        synchronized (mPageInfosCache) {
2134            mPageInfosCache.remove(new Integer JavaDoc(pageID));
2135            mVersioningPageInfosCache.remove(new Integer JavaDoc(pageID));
2136            //mPageChildIDsCache.remove(new Integer(pageID));
2137
// PagePropertyDB.getInstance().invalidateCacheForPage(pageID);
2138
mContentPageCache.remove(new Integer JavaDoc(pageID));
2139        }
2140    }
2141
2142    /**
2143     * Return the map containing the page's properties
2144     *
2145     * @param pageID
2146     * @return
2147     */

2148    public Map JavaDoc getPageProperties (int pageID)
2149        throws JahiaException {
2150        return PagePropertyDB.getInstance().getPageProperties(pageID);
2151    }
2152
2153    /**
2154     * Looks up PageProperties by using the value. This is useful when we have
2155     * unique values and we want to lookup a page by a property value.
2156     * @param propertyValue String the value used to search the properties
2157     * @throws JahiaException thrown in case there was a problem communicating
2158     * with the database.
2159     * @return ArrayList returns a list of PageProperty objects that contain
2160     * the search value.
2161     */

2162    public ArrayList JavaDoc getPagePropertiesByValue (String JavaDoc propertyValue)
2163        throws JahiaException {
2164        return PagePropertyDB.getInstance().getPagePropertiesByValue(
2165            propertyValue);
2166    }
2167    
2168    /**
2169     * Retrieve a page ID from its key and site ID.
2170     * @param pageKey
2171     * @param siteValue
2172     * @return
2173     * @throws JahiaException
2174     */

2175    public int getPageIDFromPageKeyAndSiteID( String JavaDoc pageKey, int siteID )throws JahiaException{
2176        return PagePropertyDB.getInstance().getPageIDFromPageKeyAndSiteID( pageKey, siteID );
2177    }
2178    
2179    /**
2180     * Check for page url key uniqueness.
2181     * @param key
2182     * @param siteID
2183     * @param currentPageID
2184     * @return true if given key is already used in supplied site ID.
2185     * @throws JahiaException
2186     */

2187    public boolean isKeyAlreadyUsedInSiteWithID( String JavaDoc key, int siteID, int currentPageID )
2188        throws JahiaException{
2189        return PagePropertyDB.getInstance().isKeyAlreadyUsedInSiteWithID( key, siteID, currentPageID );
2190    }
2191
2192
2193    /**
2194     * Update the ContentPage cache so that clusters are informed of the
2195     * changes.
2196     * @param contentPage ContentPage
2197     */

2198    public void updateContentPageCache(ContentPage contentPage) {
2199        mContentPageCache.put(new Integer JavaDoc(contentPage.getID()), contentPage);
2200    }
2201
2202    /**
2203     * sort pages child first
2204     *
2205     * @param pageIDs List list of pageIDs
2206     * @throws JahiaException
2207     * @return Vector
2208     */

2209    public Vector JavaDoc sortPages(List JavaDoc pageIDs, EntryLoadRequest loadRequest,
2210                            JahiaUser user, String JavaDoc operationMode)
2211    throws JahiaException {
2212        // sort pages to activate childs first
2213
Vector JavaDoc sortedPages = new Vector JavaDoc();
2214        if ( pageIDs == null ){
2215            return sortedPages;
2216        }
2217
2218        HashMap JavaDoc sortedPagePaths = new HashMap JavaDoc();
2219
2220        boolean found = false;
2221        Iterator JavaDoc iterator = pageIDs.iterator();
2222        int pos = -1;
2223        while (iterator.hasNext ()) {
2224            pos = -1;
2225            Integer JavaDoc pageId = (Integer JavaDoc) iterator.next();
2226            int size = sortedPages.size();
2227            Integer JavaDoc I = null;
2228            for (int i = 0; i < size; i++) {
2229                I = (Integer JavaDoc) sortedPages.get(i);
2230                Vector JavaDoc thePath = (Vector JavaDoc)sortedPagePaths.get(I);
2231                if ( thePath == null ){
2232                    thePath = ServicesRegistry.getInstance()
2233                        .getJahiaPageService().getContentPagePath(I.
2234                        intValue(),
2235                        loadRequest, operationMode, user);
2236                    if ( thePath != null ){
2237                        sortedPagePaths.put(I,thePath);
2238                    } else {
2239                        thePath = new Vector JavaDoc();
2240                    }
2241                }
2242                Enumeration JavaDoc enume = thePath.elements();
2243                found = false;
2244                while (enume.hasMoreElements()) {
2245                    ContentPage aPage = (ContentPage) enume.nextElement();
2246                    if (aPage.getID() == pageId.intValue()) {
2247                        pos = i;
2248                        found = true;
2249                        break;
2250                    }
2251                }
2252                if (pos != -1 && !found) {
2253                    break;
2254                }
2255            }
2256            if (pos == -1) {
2257                sortedPages.add(0,pageId);
2258            } else {
2259                sortedPages.add(pos+1,pageId);
2260            }
2261        }
2262        if ( sortedPages == null ){
2263            sortedPages = new Vector JavaDoc();
2264        }
2265        return sortedPages;
2266    }
2267
2268    public ActivationTestResults arePageFieldsValidForActivation (
2269            Set JavaDoc languageCodes,
2270            int pageID,
2271            JahiaUser user,
2272            JahiaSaveVersion saveVersion,
2273            ParamBean jParams,
2274            StateModificationContext stateModifContext)
2275            throws JahiaException {
2276
2277        Set JavaDoc fieldIDs = getStagingPageFieldIDsInPage(pageID);
2278
2279        ActivationTestResults activationResults = new ActivationTestResults ();
2280        // for each field, we check if the user has write+admin access to it,
2281
// if so we can validate it
2282
for (Iterator JavaDoc it = fieldIDs.iterator(); it.hasNext(); ) {
2283            int id = ((Integer JavaDoc) it.next()).intValue ();
2284
2285            ContentField theField = ContentField.getField (id);
2286            ActivationTestResults fieldResult = theField.isValidForActivation (languageCodes,
2287                    jParams, stateModifContext);
2288
2289            if (fieldResult.getStatus () == ActivationTestResults.FAILED_OPERATION_STATUS) {
2290                fieldResult.setStatus (ActivationTestResults.PARTIAL_OPERATION_STATUS);
2291                fieldResult.moveErrorsToWarnings ();
2292            }
2293            activationResults.merge (fieldResult);
2294        }
2295        return activationResults;
2296
2297    }
2298}
2299
Popular Tags