001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.web.repository;
017
018import java.io.IOException;
019import java.net.MalformedURLException;
020import java.util.HashMap;
021import java.util.Map;
022import java.util.Map.Entry;
023import java.util.Set;
024
025import org.apache.avalon.framework.service.ServiceException;
026import org.apache.avalon.framework.service.ServiceManager;
027import org.apache.cocoon.ProcessingException;
028import org.apache.cocoon.components.source.SourceUtil;
029import org.apache.cocoon.environment.ObjectModelHelper;
030import org.apache.cocoon.environment.Request;
031import org.apache.cocoon.generation.ServiceableGenerator;
032import org.apache.cocoon.xml.AttributesImpl;
033import org.apache.cocoon.xml.SaxBuffer;
034import org.apache.cocoon.xml.XMLUtils;
035import org.apache.commons.lang.StringUtils;
036import org.apache.commons.lang.exception.ExceptionUtils;
037import org.apache.excalibur.source.Source;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040import org.xml.sax.ContentHandler;
041import org.xml.sax.SAXException;
042
043import org.ametys.cms.content.GetContentAction;
044import org.ametys.cms.contenttype.ContentTypeDescriptor;
045import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
046import org.ametys.cms.contenttype.ContentTypesHelper;
047import org.ametys.cms.contenttype.DynamicContentTypeDescriptorExtentionPoint;
048import org.ametys.cms.repository.Content;
049import org.ametys.cms.tag.Tag;
050import org.ametys.cms.tag.TagProviderExtensionPoint;
051import org.ametys.core.DevMode;
052import org.ametys.core.DevMode.DEVMODE;
053import org.ametys.core.right.RightManager;
054import org.ametys.core.right.RightManager.RightResult;
055import org.ametys.core.ui.ClientSideElement.ScriptFile;
056import org.ametys.core.util.IgnoreRootHandler;
057import org.ametys.core.util.URIUtils;
058import org.ametys.plugins.core.ui.ObfuscatedException;
059import org.ametys.plugins.repository.AmetysObject;
060import org.ametys.plugins.repository.AmetysObjectIterable;
061import org.ametys.plugins.repository.AmetysRepositoryException;
062import org.ametys.plugins.repository.provider.WorkspaceSelector;
063import org.ametys.runtime.authentication.AccessDeniedException;
064import org.ametys.runtime.authentication.AuthorizationRequiredException;
065import org.ametys.runtime.exception.ServiceUnavailableException;
066import org.ametys.web.WebConstants;
067import org.ametys.web.cache.monitoring.Constants;
068import org.ametys.web.cache.monitoring.process.access.ResourceAccessComponent;
069import org.ametys.web.cache.monitoring.process.access.impl.PageElementResourceAccess;
070import org.ametys.web.cache.monitoring.process.access.impl.PageElementResourceAccess.PageElementType;
071import org.ametys.web.cache.monitoring.process.access.impl.PageResourceAccess;
072import org.ametys.web.cache.pageelement.PageElementCache;
073import org.ametys.web.content.ContentHelper;
074import org.ametys.web.renderingcontext.RenderingContext;
075import org.ametys.web.renderingcontext.RenderingContextHandler;
076import org.ametys.web.repository.content.SharedContent;
077import org.ametys.web.repository.page.ContentTypesAssignmentHandler;
078import org.ametys.web.repository.page.ModifiablePage;
079import org.ametys.web.repository.page.MoveablePage;
080import org.ametys.web.repository.page.Page;
081import org.ametys.web.repository.page.Page.PageType;
082import org.ametys.web.repository.page.ServicesAssignmentHandler;
083import org.ametys.web.repository.page.SitemapElement;
084import org.ametys.web.repository.page.Zone;
085import org.ametys.web.repository.page.ZoneItem;
086import org.ametys.web.repository.page.ZoneItem.ZoneType;
087import org.ametys.web.repository.site.Site;
088import org.ametys.web.service.Service;
089import org.ametys.web.service.ServiceExtensionPoint;
090import org.ametys.web.skin.Skin;
091import org.ametys.web.skin.SkinTemplate;
092import org.ametys.web.skin.SkinTemplateZone;
093import org.ametys.web.skin.SkinsManager;
094
095/**
096 * Generator for SAXing <code>Content</code> associated with a Page.<br>
097 * SAX events are like :<br>
098 * <pageContents><br>
099 *   <zone id="..."><br>
100 *     <i><!-- XHTML content --></i><br>
101 *   </zone><br>
102 *   ...<br>
103 * </pageContents/><br>
104 */
105public class PageGenerator extends ServiceableGenerator
106{
107    private ServiceExtensionPoint _serviceExtPt;
108    private ContentTypeExtensionPoint _contentTypeExtPt;
109    private SkinsManager _skinsManager;
110    private TagProviderExtensionPoint _tagProviderEP;
111    private PageElementCache _zoneItemCache;
112    private WorkspaceSelector _workspaceSelector;
113    private RenderingContextHandler _renderingContextHandler;
114    private ContentTypesHelper _contentTypeHelper;
115    private DynamicContentTypeDescriptorExtentionPoint _dynamicCTDescriptorEP;
116    
117    /** The content type assignment handler. */
118    private ContentTypesAssignmentHandler _cTypeAssignmentHandler;
119
120    /** The service assignment handler. */
121    private ServicesAssignmentHandler _serviceAssignmentHandler;
122
123    /** The resource access monitoring component */
124    private ResourceAccessComponent _resourceAccessMonitor;
125
126    /** The monitored resource access */
127    private PageResourceAccess _pageAccess;
128
129    private ContentHelper _contentHelper;
130    
131    /** The right manager */
132    private RightManager _rightManager;
133
134    private int _zoneItemsInCache;
135    private int _zoneItemsSaxed;
136    private int _zonesSaxed;
137
138    private Logger _timeLogger = LoggerFactory.getLogger("org.ametys.web.rendering.time");
139
140    @Override
141    public void service(ServiceManager serviceManager) throws ServiceException
142    {
143        super.service(serviceManager);
144        _serviceExtPt = (ServiceExtensionPoint) serviceManager.lookup(ServiceExtensionPoint.ROLE);
145        _contentTypeExtPt = (ContentTypeExtensionPoint) serviceManager.lookup(ContentTypeExtensionPoint.ROLE);
146        _skinsManager = (SkinsManager) serviceManager.lookup(SkinsManager.ROLE);
147        _tagProviderEP = (TagProviderExtensionPoint) serviceManager.lookup(TagProviderExtensionPoint.ROLE);
148        _zoneItemCache = (PageElementCache) serviceManager.lookup(PageElementCache.ROLE + "/zoneItem");
149        _workspaceSelector = (WorkspaceSelector) serviceManager.lookup(WorkspaceSelector.ROLE);
150        _renderingContextHandler = (RenderingContextHandler) serviceManager.lookup(RenderingContextHandler.ROLE);
151        _cTypeAssignmentHandler = (ContentTypesAssignmentHandler) serviceManager.lookup(ContentTypesAssignmentHandler.ROLE);
152        _serviceAssignmentHandler = (ServicesAssignmentHandler) serviceManager.lookup(ServicesAssignmentHandler.ROLE);
153        _resourceAccessMonitor = (ResourceAccessComponent) serviceManager.lookup(ResourceAccessComponent.ROLE);
154        _contentTypeHelper = (ContentTypesHelper) serviceManager.lookup(ContentTypesHelper.ROLE);
155        _dynamicCTDescriptorEP = (DynamicContentTypeDescriptorExtentionPoint) serviceManager.lookup(DynamicContentTypeDescriptorExtentionPoint.ROLE);
156        _contentHelper = (ContentHelper) serviceManager.lookup(ContentHelper.ROLE);
157        _rightManager = (RightManager) serviceManager.lookup(RightManager.ROLE);
158    }
159
160    @Override
161    public void generate() throws IOException, SAXException, ProcessingException
162    {
163        long t0 = System.currentTimeMillis();
164
165        _zoneItemsInCache = 0;
166        _zoneItemsSaxed = 0;
167        _zonesSaxed = 0;
168
169        Request request = ObjectModelHelper.getRequest(objectModel);
170
171        Page page = (Page) request.getAttribute(WebConstants.REQUEST_ATTR_PAGE);
172        String title = page.getTitle();
173
174        RenderingContext renderingContext = _renderingContextHandler.getRenderingContext();
175        String workspace = _workspaceSelector.getWorkspace();
176        String siteName = page.getSiteName();
177
178        if (page.getType() != PageType.CONTAINER)
179        {
180            throw new IllegalStateException("Cannot invoke the PageGenerator on a Page without a PageContent");
181        }
182
183        // Monitor the access to this page.
184        _pageAccess = (PageResourceAccess) request.getAttribute(Constants.REQUEST_ATTRIBUTE_PAGEACCESS);
185        
186        if (_pageAccess != null)
187        {
188            _pageAccess.setRenderingContext(renderingContext);
189            _pageAccess.setWorkspaceJCR(workspace);
190            _resourceAccessMonitor.addAccessRecord(_pageAccess);
191        }
192
193        contentHandler.startDocument();
194        AttributesImpl attrs = new AttributesImpl();
195        attrs.addCDATAAttribute("title", title);
196        attrs.addCDATAAttribute("long-title", page.getLongTitle());
197        attrs.addCDATAAttribute("id", page.getId());
198        XMLUtils.startElement(contentHandler, "page", attrs);
199
200        try
201        {
202            XMLUtils.startElement(contentHandler, "metadata");
203            page.dataToSAX(contentHandler);
204            XMLUtils.endElement(contentHandler, "metadata");
205
206            // Tags
207            XMLUtils.startElement(contentHandler, "tags");
208            Set<String> tags = page.getTags();
209            for (String tagName : tags)
210            {
211                Map<String, Object> contextParameters = new HashMap<>();
212                contextParameters.put("siteName", siteName);
213                
214                Tag tag = _tagProviderEP.getTag(tagName, contextParameters);
215
216                if (tag != null)
217                {
218                    // tag may be null if it has been registered on the page and then removed from the application
219                    AttributesImpl tagattrs = new AttributesImpl();
220                    if (tag.getParentName() != null)
221                    {
222                        tagattrs.addCDATAAttribute("parent", tag.getParentName());
223                    }
224
225                    XMLUtils.startElement(contentHandler, tagName, tagattrs);
226                    tag.getTitle().toSAX(contentHandler);
227                    XMLUtils.endElement(contentHandler, tagName);
228                }
229            }
230            XMLUtils.endElement(contentHandler, "tags");
231        }
232        catch (AmetysRepositoryException e)
233        {
234            _pageAccess = null;
235            throw new ProcessingException("Unable to SAX page metadata", e);
236        }
237
238        long t1 = System.currentTimeMillis();
239
240        AttributesImpl pcattrs = new AttributesImpl();
241        pcattrs.addCDATAAttribute("modifiable", Boolean.toString(page instanceof ModifiablePage));
242        pcattrs.addCDATAAttribute("moveable", Boolean.toString(page instanceof MoveablePage));
243        XMLUtils.startElement(contentHandler, "pageContents", pcattrs);
244
245        try
246        {
247            // Iterate on existing zones
248            for (Zone zone : page.getZones())
249            {
250                String zoneName = zone.getName();
251                AmetysObjectIterable<? extends ZoneItem> zoneItems = zone.getZoneItems();
252
253                _saxZone(page, zoneName, zoneItems, workspace, siteName, renderingContext);
254            }
255
256            // Iterate on defined zone (that are not existing)
257            SkinTemplate skinTemplate = _getTemplateDefinition(page);
258            if (skinTemplate != null)
259            {
260                for (SkinTemplateZone zoneDef : skinTemplate.getZones().values())
261                {
262                    if (!page.hasZone(zoneDef.getId()))
263                    {
264                        _saxZone(page, zoneDef.getId(), null, workspace, siteName, renderingContext);
265                    }
266                }
267            }
268        }
269        catch (AmetysRepositoryException ex)
270        {
271            _pageAccess = null;
272            throw new ProcessingException("Unable to get Content", ex);
273        }
274
275        long t2 = System.currentTimeMillis();
276        _timeLogger.debug("Zones processing time: {} ms", t2 - t1);
277        if (getLogger().isInfoEnabled())
278        {
279            getLogger().info("PageGenerator\t/" + page.getSiteName() + "/" + page.getSitemapName() + "/" + page.getPathInSitemap() + "\t" + page.getId() + "\tprocessing time (in ms):\t" + (t2 - t0) + "\tRendering context:\t" + renderingContext + "\tSaxing (zones, total zoneItems, zoneItems from cache):\t" + _zonesSaxed + "\t" + _zoneItemsSaxed + "\t" + _zoneItemsInCache);
280        }
281
282        XMLUtils.endElement(contentHandler, "pageContents");
283        XMLUtils.endElement(contentHandler, "page");
284        contentHandler.endDocument();
285
286        _timeLogger.debug("Page processing time: {} ms", t2 - t0);
287
288        _pageAccess = null;
289    }
290
291    /**
292     * Sax a zone
293     * @param page The page
294     * @param zoneName The zone in the page to sax
295     * @param zoneItems The items of the zone or null
296     * @param workspace the workspace
297     * @param site the site's name
298     * @param renderingContext the rendering context
299     * @throws SAXException if an error occurs while saxing
300     * @throws IOException if an I/O exception occurs
301     * @throws ProcessingException if an error occurs
302     */
303    private void _saxZone(Page page, String zoneName, AmetysObjectIterable<? extends ZoneItem> zoneItems, String workspace, String site, RenderingContext renderingContext) throws SAXException, IOException, ProcessingException
304    {
305        _zonesSaxed++;
306
307        AmetysObjectIterable<? extends ZoneItem> localZoneItems = zoneItems;
308
309        AttributesImpl zoneAttrs = new AttributesImpl();
310        zoneAttrs.addCDATAAttribute("name", zoneName);
311
312        if (localZoneItems == null || !localZoneItems.iterator().hasNext())
313        {
314            // zone is empty => try to inherit
315            Zone parentPageZone = _inherit(page, page, zoneName);
316            if (parentPageZone != null)
317            {
318                zoneAttrs.addCDATAAttribute("inherited", parentPageZone.getSitemapElement().getId());
319
320                localZoneItems = parentPageZone.getZoneItems();
321            }
322        }
323
324        Request request = ObjectModelHelper.getRequest(objectModel);
325        request.setAttribute(Zone.class.getName(), zoneName);
326
327        XMLUtils.startElement(contentHandler, "zone", zoneAttrs);
328
329        _saxAvailableContentTypes(page, zoneName);
330        _saxAvailableServices(page, zoneName);
331
332        _saxZoneItems(page, localZoneItems, workspace, site, renderingContext);
333
334        XMLUtils.endElement(contentHandler, "zone");
335        request.setAttribute(Zone.class.getName(), null);
336
337    }
338
339    /**
340     * Generate the list of available services for the given zone.
341     * @param page the page.
342     * @param zoneName the zone name in the page.
343     * @throws SAXException if something goes wrong when saxing the available services
344     */
345    private void _saxAvailableServices(Page page, String zoneName) throws SAXException
346    {
347        Set<String> services = _serviceAssignmentHandler.getAvailableServices(page, zoneName);
348
349        XMLUtils.startElement(contentHandler, "available-services");
350
351        for (String service : services)
352        {
353            AttributesImpl attrs = new AttributesImpl();
354            attrs.addCDATAAttribute("id", service);
355            XMLUtils.createElement(contentHandler, "service", attrs);
356        }
357
358        XMLUtils.endElement(contentHandler, "available-services");
359    }
360
361    /**
362     * Generate the list of available content types for the given zone.
363     * @param page the page.
364     * @param zoneName the zone name in the page.
365     * @throws SAXException if something goes wrong when saxing the available content types
366     */
367    private void _saxAvailableContentTypes(Page page, String zoneName) throws SAXException
368    {
369        Set<String> cTypes = _cTypeAssignmentHandler.getAvailableContentTypes(page, zoneName, true);
370
371        XMLUtils.startElement(contentHandler, "available-content-types");
372
373        for (String cType : cTypes)
374        {
375            AttributesImpl attrs = new AttributesImpl();
376            attrs.addCDATAAttribute("id", cType);
377            XMLUtils.createElement(contentHandler, "content-type", attrs);
378        }
379
380        XMLUtils.endElement(contentHandler, "available-content-types");
381    }
382
383    /**
384     * Sax zone items
385     * @param page the page
386     * @param zoneItems The zone items to sax
387     * @param workspace the workspace
388     * @param site the site's name
389     * @param renderingContext the rendering context
390     * @throws SAXException if an error occurs while saxing
391     * @throws IOException if an I/O exception occurs
392     * @throws ProcessingException if an error occurs
393     */
394    private void _saxZoneItems(Page page, AmetysObjectIterable< ? extends ZoneItem> zoneItems, String workspace, String site, RenderingContext renderingContext) throws SAXException, IOException, ProcessingException
395    {
396        if (zoneItems == null)
397        {
398            return;
399        }
400
401        Request request = ObjectModelHelper.getRequest(objectModel);
402
403        for (ZoneItem zoneItem : zoneItems)
404        {
405            _saxZoneItem(page, workspace, site, renderingContext, request, zoneItem);
406        }
407    }
408    
409    private void _handleZoneAccess(PageElementResourceAccess zoneAccess, boolean cacheable, boolean hit)
410    {
411        if (zoneAccess != null)
412        {
413            zoneAccess.setCacheable(cacheable);
414            zoneAccess.setCacheHit(hit);
415        }
416    }
417
418    private void _saxZoneItem(Page page, String workspace, String site, RenderingContext renderingContext, Request request, ZoneItem zoneItem) throws SAXException, ProcessingException, IOException
419    {
420        long t0 = System.currentTimeMillis();
421
422        _zoneItemsSaxed++;
423
424        String id = zoneItem.getId();
425        ZoneType type = zoneItem.getType();
426
427        request.setAttribute(WebConstants.REQUEST_ATTR_ZONEITEM, zoneItem);
428
429        AttributesImpl zoneItemAttrs = new AttributesImpl();
430        zoneItemAttrs.addCDATAAttribute("id", id);
431
432        PageElementResourceAccess zoneAccess = _pageAccess != null ? _pageAccess.createPageElementAccess(id, PageElementType.fromZoneItemType(type)) : null;
433
434        // try to get content from cache only if it is cacheable
435        SaxBuffer cachedContent = null;
436        Exception ex = null;
437
438        boolean isCacheable = false;
439        if (type == ZoneType.CONTENT)
440        {
441            // a Content is always cacheable
442            isCacheable = true;
443        }
444        else if (type == ZoneType.SERVICE)
445        {
446            String serviceId = zoneItem.getServiceId();
447            Service service = _serviceExtPt.getExtension(serviceId);
448
449            if (service != null)
450            {
451                try
452                {
453                    isCacheable = service.isCacheable(page, zoneItem);
454                }
455                catch (Exception e)
456                {
457                    ex = new ProcessingException("Error testing the service cachability.", e);
458                }
459            }
460            // if service is null, an exception will be thrown later
461        }
462
463        _handleZoneAccess(zoneAccess, isCacheable, false);
464        
465        request.setAttribute("IsZoneItemCacheable", isCacheable);
466        
467        if (isCacheable)
468        {
469            cachedContent = _zoneItemCache.getPageElement(workspace, site, _getType(zoneItem), id, page.getId(), renderingContext);
470        }
471        
472        if (cachedContent != null)
473        {
474            _handleZoneAccess(zoneAccess, true, true);
475            
476            _zoneItemsInCache++;
477            
478            request.setAttribute("IsZoneItemCacheable", true);
479
480            cachedContent.toSAX(contentHandler);
481        }
482        else
483        {
484
485            SaxBuffer buffer = null;
486            ContentHandler handler; // the actual ContentHandler, either the real one, or a buffer
487            if (isCacheable)
488            {
489                buffer = new SaxBuffer();
490                handler = buffer;
491            }
492            else
493            {
494                handler = contentHandler;
495            }
496
497            XMLUtils.startElement(handler, "zoneItem", zoneItemAttrs);
498
499            XMLUtils.startElement(handler, "information");
500            XMLUtils.createElement(handler, "type", type.toString());
501
502            Object result = null;
503            if (type == ZoneType.CONTENT)
504            {
505                if (getLogger().isDebugEnabled())
506                {
507                    Content content = zoneItem.getContent();
508                    getLogger().debug("Processing content " + content.getId() + " / " + content.getPath());
509                }
510                
511                result = _saxContentZoneItem(zoneItem, handler, request);
512            }
513            else if (type == ZoneType.SERVICE)
514            {
515                if (getLogger().isDebugEnabled())
516                {
517                    getLogger().debug("Processing service " + zoneItem.getServiceId());
518                }
519                
520                result = _saxServiceZoneItem(zoneItem, handler, ex);
521            }
522
523            Source src = null;
524            if (result instanceof Source)
525            {
526                src = (Source) result;
527            }
528            else
529            {
530                ex = (Exception) result;
531            }
532            
533            XMLUtils.endElement(handler, "information");
534
535            _saxSource(handler, src, ex, isCacheable);
536
537            XMLUtils.endElement(handler, "zoneItem");
538
539            // finally store the buffered data in the cache and SAX it to the pipeline
540            if (buffer != null)
541            {
542                buffer.toSAX(contentHandler);
543                _zoneItemCache.storePageElement(workspace, site, _getType(zoneItem), id, page.getId(), renderingContext, buffer);
544            }
545        }
546
547        // Monitor the access to this zone item.
548        _resourceAccessMonitor.addAccessRecord(zoneAccess);
549
550        // Empty content request attributes
551        request.setAttribute(Content.class.getName(), null);
552        // Empty zone item request attribute
553        request.setAttribute(WebConstants.REQUEST_ATTR_ZONEITEM, null);
554        // Empty zone item cacheable attribute
555        request.setAttribute("IsZoneItemCacheable", null);
556        
557        _timeLogger.debug("Zone item {} processing time: {} ms", id, System.currentTimeMillis() - t0);
558    }
559    
560    private Object _saxContentZoneItem(ZoneItem zoneItem, ContentHandler handler, Request request) throws SAXException, MalformedURLException, IOException
561    {
562        try
563        {
564            Content content = zoneItem.getContent();
565            String viewName = StringUtils.defaultString(zoneItem.getViewName(), "main");
566
567            XMLUtils.createElement(handler, "contentId", content.getId());
568            XMLUtils.createElement(handler, "contentName", content.getName());
569            XMLUtils.createElement(handler, "metadataSetName", viewName);
570            if (content instanceof SharedContent)
571            {
572                XMLUtils.createElement(handler, "sharedContent", "true");
573            }
574
575            String contentTypeId = _contentTypeHelper.getContentTypeIdForRendering(content);
576            
577            ContentTypeDescriptor contentType = _contentTypeExtPt.getExtension(contentTypeId);
578            if (contentType == null)
579            {
580                contentType = _dynamicCTDescriptorEP.getExtension(contentTypeId);
581            }
582            
583            if (contentType == null)
584            {
585                return new IllegalStateException("The content type '" + contentTypeId + "' is referenced but does not exist");
586            }
587            else
588            {
589                AttributesImpl contentTypeAttrs = new AttributesImpl();
590                contentTypeAttrs.addCDATAAttribute("id", contentType.getId());
591                XMLUtils.startElement(handler, "type-information", contentTypeAttrs);
592
593                contentType.getLabel().toSAX(handler, "label");
594                contentType.getDescription().toSAX(handler, "description");
595                
596                if (contentType.getIconGlyph() != null)
597                {
598                    XMLUtils.createElement(handler, "iconGlyph", contentType.getIconGlyph());
599                }
600                if (contentType.getIconDecorator() != null)
601                {
602                    XMLUtils.createElement(handler, "iconDecorator", contentType.getIconDecorator());
603                }
604                
605                if (contentType.getSmallIcon() != null)
606                {
607                    XMLUtils.createElement(handler, "smallIcon", contentType.getSmallIcon());
608                    XMLUtils.createElement(handler, "mediumIcon", contentType.getMediumIcon());
609                    XMLUtils.createElement(handler, "largeIcon", contentType.getLargeIcon());
610                }
611                
612                XMLUtils.startElement(handler, "css");
613                for (ScriptFile cssFile : contentType.getCSSFiles())
614                {
615                    _saxCSSFile(handler, cssFile);
616                }
617                XMLUtils.endElement(handler, "css");
618                
619                XMLUtils.endElement(handler, "type-information");
620
621                String url = "cocoon://_plugins/" + contentType.getPluginName() + "/" + contentType.getId() + ".html";
622                Map<String, String> urlParams = _contentHelper.getContentViewUrlParameters(content, viewName, "html");
623                
624                // FIXME use a context
625                request.setAttribute(Content.class.getName(), content);
626                request.setAttribute(GetContentAction.RESULT_CONTENTTYPE, contentTypeId);
627                return resolver.resolveURI(URIUtils.buildURI(url, urlParams));
628            }
629        }
630        catch (AmetysRepositoryException e)
631        {
632            return new ProcessingException("Unable to get content property", e);
633        }
634    }
635    
636    private Object _saxServiceZoneItem(ZoneItem zoneItem, ContentHandler handler, Exception ex) throws SAXException, MalformedURLException, IOException
637    {
638        String serviceId = zoneItem.getServiceId();
639        Service service = _serviceExtPt.getExtension(serviceId);
640
641        if (service == null)
642        {
643            return new ProcessingException("Unable to get service for name '" + serviceId + "'");
644        }
645        else if (ex == null) // If an exception was caught while testing the service cacheability, do not generate
646        {
647            AttributesImpl serviceAttrs = new AttributesImpl();
648            serviceAttrs.addCDATAAttribute("id", service.getId());
649            XMLUtils.startElement(handler, "type-information", serviceAttrs);
650
651            service.getLabel().toSAX(handler, "label");
652            service.getDescription().toSAX(handler, "description");
653            
654            if (service.getIconGlyph() != null)
655            {
656                XMLUtils.createElement(handler, "iconGlyph", service.getIconGlyph());
657            }
658            if (service.getIconDecorator() != null)
659            {
660                XMLUtils.createElement(handler, "iconDecorator", service.getIconDecorator());
661            }
662            if (service.getSmallIcon() != null)
663            {
664                XMLUtils.createElement(handler, "smallIcon", service.getSmallIcon());
665                XMLUtils.createElement(handler, "mediumIcon", service.getMediumIcon());
666            }
667            
668            XMLUtils.startElement(handler, "css");
669            for (ScriptFile cssFile : service.getCSSFiles())
670            {
671                _saxCSSFile(handler, cssFile);
672            }
673            XMLUtils.endElement(handler, "css");
674            
675            XMLUtils.endElement(handler, "type-information");
676
677            return resolver.resolveURI(service.getURL(), null, PageGeneratorHelper.getParameters(service, zoneItem));
678        }
679        else
680        {
681            return ex;
682        }
683    }
684    
685    private void _saxCSSFile(ContentHandler handler, ScriptFile cssFile) throws SAXException
686    {
687        AttributesImpl fileAttrs = new AttributesImpl();
688        if (!cssFile.isLangSpecific())
689        {
690            String rtlMode = cssFile.getRtlMode();
691            if (rtlMode != null && !"all".equals(rtlMode))
692            {
693                fileAttrs.addCDATAAttribute("rtl", rtlMode);
694            }
695            
696            XMLUtils.createElement(handler, "file", fileAttrs, cssFile.getPath());
697        }
698        else
699        {
700            fileAttrs.addCDATAAttribute("lang", "true");
701            XMLUtils.startElement(handler, "file", fileAttrs);
702            
703            String defaultLang = cssFile.getDefaultLang();
704            Map<String, String> langPaths = cssFile.getLangPaths();
705            
706            for (Entry<String, String> langPath : langPaths.entrySet())
707            {
708                AttributesImpl langAttrs = new AttributesImpl();
709                
710                String codeLang = langPath.getKey();
711                langAttrs.addCDATAAttribute("code", codeLang);
712                if (codeLang.equals(defaultLang))
713                {
714                    langAttrs.addCDATAAttribute("default", "true");
715                }
716                
717                XMLUtils.createElement(handler, "lang", langAttrs, langPath.getValue());
718            }
719
720            XMLUtils.endElement(handler, "file");
721        }
722    }
723
724    private void _saxSource(ContentHandler handler, Source src, Exception ex, boolean isCacheable) throws SAXException, IOException, ProcessingException
725    {
726        if (src == null)
727        {
728            Throwable e = _obfuscate(ex, isCacheable);
729            if (e instanceof ObfuscatedException obfuscatedException)
730            {
731                obfuscatedException.reveal();
732                getLogger().error("Unable to display zone item", ex);
733                obfuscatedException.obfuscate();
734            }
735            else
736            {
737                getLogger().error("Unable to display zone item", ex);
738            }
739            
740            _saxError(handler, e);
741        }
742        else
743        {
744            try
745            {
746                SourceUtil.toSAX(src, new IgnoreRootHandler(handler));
747            }
748            catch (ProcessingException e)
749            {
750                if (_throwException(e))
751                {
752                    getLogger().error("Unable to display zone item", e);
753                    throw e;
754                }
755                else
756                {
757                    Throwable cause = _obfuscate(e.getCause(), isCacheable);
758                    if (cause instanceof ObfuscatedException obfuscatedException)
759                    {
760                        obfuscatedException.reveal();
761                        getLogger().error("Unable to display zone item", cause);
762                        obfuscatedException.obfuscate();
763                    }
764                    else
765                    {
766                        getLogger().error("Unable to display zone item", cause);
767                    }
768                    _saxError(handler, cause);
769                }
770            }
771            finally
772            {
773                resolver.release(src);
774            }
775        }
776    }
777
778    private String _getType(ZoneItem zoneItem)
779    {
780        ZoneType type = zoneItem.getType();
781
782        if (type == ZoneType.CONTENT)
783        {
784            return "CONTENT";
785        }
786        else
787        {
788            return "SERVICE:" + zoneItem.getServiceId();
789        }
790    }
791
792    /**
793     * Get the template definition for a page
794     * @param sitemapElement The page. Cannot be null.
795     * @return The template definition. Null if the page is not a container or if the template is not declared.
796     */
797    private SkinTemplate _getTemplateDefinition(SitemapElement sitemapElement)
798    {
799        String templateName = sitemapElement.getTemplate();
800        if (templateName == null)
801        {
802            return null;
803        }
804
805        Site site = sitemapElement.getSite();
806        String skinId = site.getSkinId();
807        try
808        {
809            Skin skinDef = _skinsManager.getSkin(skinId);
810            return skinDef.getTemplate(templateName);
811        }
812        catch (IllegalStateException e)
813        {
814            getLogger().error("Cannot get template definition for page '" + sitemapElement.getId() + "' using template '" + templateName + "' in skin '" + skinId + "'");
815            return null;
816        }
817    }
818
819    /**
820     * Try to inherit the zone (as it is empty)
821     * @param childPage The child page that do inherit. Cannot be null
822     * @param page The page to inherit. Cannot be null
823     * @param zoneName The zone name in the page to inherit. Cannot be null or empty
824     * @return The zone inherited or null.
825     */
826    private Zone _inherit(Page childPage, SitemapElement page, String zoneName)
827    {
828        // The page has an existing zone at this place ?
829        if (page.hasZone(zoneName))
830        {
831            Zone zone = page.getZone(zoneName);
832            AmetysObjectIterable<? extends ZoneItem> zoneItems = zone.getZoneItems();
833
834            // With data ?
835            if (zoneItems.iterator().hasNext())
836            {
837                // This is it (end of the recursion)
838                return zone;
839            }
840        }
841
842        // Get the definition for the zone
843        SkinTemplateZone zoneDef;
844
845        Site site = page.getSite();
846        String skinId = site.getSkinId();
847        String templateName = page.getTemplate();
848        try
849        {
850            SkinTemplate templateDef = _getTemplateDefinition(page);
851            zoneDef = templateDef.getZone(zoneName);
852        }
853        catch (IllegalStateException e)
854        {
855            getLogger().error("The page '" + childPage.getId() + "' cannot inherit a zone '" + zoneName + "' of template '" + templateName + "' in skin '" + skinId + "' as asked for page '" + page.getId() + "' in site '" + site.getName() + "'", e);
856            return null;
857        }
858
859        // This zone is not defined for the template
860        if (zoneDef == null)
861        {
862            getLogger().warn("The page '" + childPage.getId() + "' cannot inherit the undefined zone '" + zoneName + "' of template '" + templateName + "' in skin '" + skinId + "' as asked for page '" + page.getId() + "' in site '" + site.getName() + "'.");
863            return null;
864        }
865
866        // Support inheritance ?
867        if (!zoneDef.hasInheritance())
868        {
869            return null;
870        }
871
872        // Get the parent page (that is a container page)
873        SitemapElement parentPage = page;
874        do
875        {
876            AmetysObject parentObject = parentPage.getParent();
877            if (parentObject instanceof SitemapElement pc)
878            {
879                parentPage = pc;
880            }
881            else
882            {
883                // inheritance goes back to the root
884                return null;
885            }
886        }
887        while (parentPage.getTemplate() == null);
888
889        // Get the name of the zone which will be the inheritance source
890        String parentPageTemplate = parentPage.getTemplate();
891        String inheritanceSrc = zoneDef.getInheritance(parentPageTemplate);
892        if (inheritanceSrc == null)
893        {
894            // No inheritance for this template
895            return null;
896        }
897
898        // Finally we will inherit from the parentPage and the zone inheritanceSrc
899        return _inherit(childPage, parentPage, inheritanceSrc);
900    }
901
902    /**
903     * Test if the error has to be thrown instead of SAXing it as an error zone item.
904     * @param ex the exception.
905     * @return true to throw the exception, false to catch it and SAX it as an error zone item.
906     */
907    private boolean _throwException(Exception ex)
908    {
909        return _renderingContextHandler.getRenderingContext() == RenderingContext.FRONT
910            && (
911                _isExceptionType(ex, AuthorizationRequiredException.class)
912                || _isExceptionType(ex, AccessDeniedException.class)
913                // See CMS-12302 if you want to change that one day
914                || _isExceptionType(ex, ServiceUnavailableException.class)
915            );
916    }
917    
918    private boolean _isExceptionType(Throwable throwable, Class clazz)
919    {
920        return ExceptionUtils.indexOfThrowable(throwable, clazz) > -1;
921    }
922
923    private void _saxError(ContentHandler handler, Throwable e) throws SAXException
924    {
925        XMLUtils.startElement(handler, "zone-item-error");
926        
927        XMLUtils.createElement(handler, "exception-message", e != null ? StringUtils.defaultString(e.getMessage()) : "");
928        XMLUtils.createElement(handler, "exception-stack-trace", StringUtils.defaultString(ExceptionUtils.getFullStackTrace(e)));
929        
930        XMLUtils.endElement(handler, "zone-item-error");
931    }
932    
933    private Throwable _obfuscate(Throwable throwable, boolean isCacheable)
934    {
935        if (!DEVMODE.PRODUCTION.equals(DevMode.getDeveloperMode()) // Do not read dev mode from request to prevent override from request param
936                || !isCacheable && _rightManager.currentUserHasRight("Runtime_Rights_Admin_Access", "/admin").equals(RightResult.RIGHT_ALLOW))
937        {
938            return throwable;
939        }
940        else
941        {
942            return ObfuscatedException.obfuscate(throwable);
943        }
944    }
945}