View Javadoc

1   /**
2    * This file Copyright (c) 2011-2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.templating.elements;
35  
36  import info.magnolia.cms.beans.config.ServerConfiguration;
37  import info.magnolia.cms.core.MetaData;
38  import info.magnolia.cms.core.MgnlNodeType;
39  import info.magnolia.cms.i18n.Messages;
40  import info.magnolia.cms.i18n.MessagesManager;
41  import info.magnolia.context.MgnlContext;
42  import info.magnolia.context.WebContext;
43  import info.magnolia.jcr.RuntimeRepositoryException;
44  import info.magnolia.jcr.util.ContentMap;
45  import info.magnolia.jcr.util.NodeUtil;
46  import info.magnolia.objectfactory.Components;
47  import info.magnolia.rendering.context.RenderingContext;
48  import info.magnolia.rendering.engine.AppendableOnlyOutputProvider;
49  import info.magnolia.rendering.engine.RenderException;
50  import info.magnolia.rendering.engine.RenderingEngine;
51  import info.magnolia.rendering.template.AreaDefinition;
52  import info.magnolia.rendering.template.AutoGenerationConfiguration;
53  import info.magnolia.rendering.template.ComponentAvailability;
54  import info.magnolia.rendering.template.RenderableDefinition;
55  import info.magnolia.rendering.template.TemplateDefinition;
56  import info.magnolia.rendering.template.configured.ConfiguredAreaDefinition;
57  import info.magnolia.templating.freemarker.AbstractDirective;
58  import info.magnolia.templating.inheritance.DefaultInheritanceContentDecorator;
59  import info.magnolia.templating.renderers.NoScriptRenderer;
60  
61  import java.io.IOException;
62  import java.util.ArrayList;
63  import java.util.Collection;
64  import java.util.HashMap;
65  import java.util.Iterator;
66  import java.util.List;
67  import java.util.Map;
68  
69  import javax.jcr.Node;
70  import javax.jcr.RepositoryException;
71  import javax.jcr.Session;
72  
73  import org.apache.commons.collections.CollectionUtils;
74  import org.apache.commons.lang.StringUtils;
75  import org.apache.jackrabbit.JcrConstants;
76  import org.slf4j.Logger;
77  import org.slf4j.LoggerFactory;
78  
79  /**
80   * Renders an area and outputs a marker that instructs the page editor to place a bar at this location.
81   *
82   * @version $Id$
83   */
84  public class AreaElement extends AbstractContentTemplatingElement {
85  
86      private static final Logger log = LoggerFactory.getLogger(AreaElement.class);
87      public static final String CMS_AREA = "cms:area";
88  
89      public static final String ATTRIBUTE_COMPONENT = "component";
90      public static final String ATTRIBUTE_COMPONENTS = "components";
91  
92      public static final String SHOW_NEW_COMPONENT_AREA = "showNewComponentArea";
93      public static final String SHOW_ADD_BUTTON = "showAddButton";
94  
95      private final RenderingEngine renderingEngine;
96  
97      private Node areaNode;
98      private TemplateDefinition templateDefinition;
99      private AreaDefinition areaDefinition;
100     private String name;
101     private String type;
102     private String dialog;
103     private String availableComponents;
104     private String label;
105     private String description;
106     private Boolean inherit;
107     private Boolean optional;
108     private Boolean editable;
109     private Integer maxComponents;
110 
111     private Map<String, Object> contextAttributes = new HashMap<String, Object>();
112 
113     private String areaPath;
114 
115     private boolean isAreaDefinitionEnabled;
116 
117 
118     public AreaElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine) {
119         super(server, renderingContext);
120         this.renderingEngine = renderingEngine;
121     }
122 
123     @Override
124     public void begin(Appendable out) throws IOException, RenderException {
125 
126         this.templateDefinition = resolveTemplateDefinition();
127         this.areaDefinition = resolveAreaDefinition();
128         this.isAreaDefinitionEnabled = areaDefinition != null && (areaDefinition.getEnabled() == null || areaDefinition.getEnabled());
129 
130         if (!this.isAreaDefinitionEnabled) {
131             return;
132         }
133         // set the values based on the area definition if not passed
134         this.name = resolveName();
135         this.dialog = resolveDialog();
136         this.type = resolveType();
137         this.label = resolveLabel();
138         this.availableComponents = resolveAvailableComponents();
139         this.inherit = isInheritanceEnabled();
140         this.optional = resolveOptional();
141         this.editable = resolveEditable();
142 
143         this.description = templateDefinition.getDescription();
144 
145         // build an adhoc area definition if no area definition can be resolved
146         if (this.areaDefinition == null) {
147             buildAdHocAreaDefinition();
148         }
149 
150         this.maxComponents = resolveMaximumOfComponents();
151 
152         // read area node and calculate the area path
153         this.areaNode = getPassedContent();
154         if (this.areaNode != null) {
155             this.areaPath = getNodePath(areaNode);
156         } else {
157             // will be null if no area has been created (for instance for optional areas)
158             // current content is the parent node
159             Node parentNode = currentContent();
160             this.areaNode = tryToCreateAreaNode(parentNode);
161             this.areaPath = getNodePath(parentNode) + "/" + name;
162         }
163 
164         if (isAdmin() && hasPermission(this.areaNode)) {
165             MarkupHelper helper = new MarkupHelper(out);
166 
167             helper.openComment(CMS_AREA).attribute(AbstractDirective.CONTENT_ATTRIBUTE, this.areaPath);
168             helper.attribute("name", this.name);
169             helper.attribute("availableComponents", this.availableComponents);
170             helper.attribute("type", this.type);
171             helper.attribute("dialog", this.dialog);
172 
173             final String i18nBasename = StringUtils.isNotEmpty(areaDefinition.getI18nBasename()) ? areaDefinition.getI18nBasename() : templateDefinition.getI18nBasename();
174             Messages messages = MessagesManager.getMessages(i18nBasename);
175             helper.attribute("label", messages.getWithDefault(this.label, this.label));
176 
177             helper.attribute("inherit", String.valueOf(this.inherit));
178             if (this.editable != null) {
179                 helper.attribute("editable", String.valueOf(this.editable));
180             }
181             helper.attribute("optional", String.valueOf(this.optional));
182             if (isOptionalAreaCreated()) {
183                 helper.attribute("created", "true");
184             }
185             helper.attribute(SHOW_ADD_BUTTON, String.valueOf(shouldShowAddButton()));
186             helper.attribute(SHOW_NEW_COMPONENT_AREA, String.valueOf(shouldShowNewComponentArea()));
187 
188             if (StringUtils.isNotBlank(description)) {
189                 helper.attribute("description", messages.getWithDefault(description, description));
190             }
191 
192             helper.append(" -->\n");
193 
194         }
195     }
196 
197     private boolean hasPermission(Node node) {
198         if (node == null) {
199             node = currentContent();
200         }
201         try {
202             return node.getSession().hasPermission(node.getPath(), Session.ACTION_SET_PROPERTY);
203         } catch (RepositoryException e) {
204             log.error("Could not determine permission for node {}", node);
205         }
206         return false;
207     }
208 
209     private Node createNewAreaNode(Node parentNode) throws RepositoryException {
210         final String parentId = parentNode.getIdentifier();
211         final String workspaceName = parentNode.getSession().getWorkspace().getName();
212         try {
213             MgnlContext.doInSystemContext(new MgnlContext.Op<Void, RepositoryException>() {
214                 @Override
215                 public Void exec() throws RepositoryException {
216                     Node parentNodeInSystemSession = NodeUtil.getNodeByIdentifier(workspaceName, parentId);
217                     Node newAreaNode = NodeUtil.createPath(parentNodeInSystemSession, AreaElement.this.name, MgnlNodeType.NT_AREA);
218                     NodeUtil.createPath(newAreaNode, MetaData.DEFAULT_META_NODE, MgnlNodeType.NT_METADATA);
219                     newAreaNode.getSession().save();
220                     return null;
221                 }
222             });
223         } catch (RepositoryException e) {
224             final String parentPath = parentNode.getPath();
225             if (parentPath.startsWith("/" + JcrConstants.JCR_SYSTEM)) {
226                 log.warn("Could not autogenerate area in workspace {} for node {} because it is read-only. Pls preview page before versioning to avoid this issue", workspaceName, parentPath);
227             } else {
228                 log.error("Could not autogenerate area in workspace " + workspaceName + " for node " + parentPath, e);
229             }
230             return null;
231         }
232         // new node has been created in SystemContext - if it's now not around in user session, then just because JCR repo did not refresh yet.
233         // We try few times then we give up
234         for (int i = 0; i < 5; i++) {
235             if (parentNode.hasNode(this.name)) {
236                 return parentNode.getNode(this.name);
237             }
238             log.debug("New node {} is not yet visible in session for user {} - will try again after short sleep.", NodeUtil.combinePathAndName(parentNode.getPath(), this.name), MgnlContext.getUser().getName());
239             try {
240                 Thread.sleep(100);
241             } catch (InterruptedException e) {
242                 log.debug("Exception when waiting before next session refresh", e);
243                 Thread.interrupted();
244             }
245             parentNode.refresh(true);
246         }
247         log.warn("New node {} is still not visible in session for user {}. It seems your server is busy - you might want to increase assigned resources", NodeUtil.combinePathAndName(parentNode.getPath(), this.name), MgnlContext.getUser().getName());
248         return null;
249     }
250 
251     protected void buildAdHocAreaDefinition() {
252         ConfiguredAreaDefinition addHocAreaDefinition = new ConfiguredAreaDefinition();
253         addHocAreaDefinition.setName(this.name);
254         addHocAreaDefinition.setDialog(this.dialog);
255         addHocAreaDefinition.setType(this.type);
256         addHocAreaDefinition.setRenderType(this.templateDefinition.getRenderType());
257         areaDefinition = addHocAreaDefinition;
258     }
259 
260     @Override
261     public void end(Appendable out) throws RenderException {
262 
263         try {
264             if (canRenderAreaScript()) {
265                 if (isInherit() && areaNode != null && areaDefinition.getInheritance() != null) {
266                     try {
267                         areaNode = new DefaultInheritanceContentDecorator(areaNode, areaDefinition.getInheritance()).wrapNode(areaNode);
268                     } catch (RepositoryException e) {
269                         throw new RuntimeRepositoryException(e);
270                     }
271                 }
272                 List<Node> listOfComponents = null;
273                 int numberOfComponents = 0;
274                 if (areaNode != null) {
275                     listOfComponents = NodeUtil.asList(NodeUtil.getNodes(areaNode, MgnlNodeType.NT_COMPONENT));
276                     numberOfComponents = listOfComponents.size();
277                 }
278                 if (renderingEngine.getRenderEmptyAreas() || numberOfComponents > 0 || !(AreaDefinition.TYPE_LIST.equals(areaDefinition.getType()) || AreaDefinition.TYPE_SINGLE.equals(areaDefinition.getType()))) {
279 
280                     Map<String, Object> contextObjects = new HashMap<String, Object>();
281 
282                     List<ContentMap> components = new ArrayList<ContentMap>();
283 
284                     if (areaNode != null) {
285                         if (numberOfComponents > maxComponents) {
286                             listOfComponents = listOfComponents.subList(0, maxComponents);
287                             log.warn("The area {} have maximum number of components set to {}, but has got " + numberOfComponents +
288                                     " components. Exceeded components won't be added.", areaNode, maxComponents);
289                         }
290 
291                         for (Node node : listOfComponents) {
292                             components.add(new ContentMap(node));
293                         }
294                     }
295 
296                     if (AreaDefinition.TYPE_SINGLE.equals(type)) {
297                         if (components.size() > 1) {
298                             throw new RenderException("Can't render single area [" + areaNode + "]: expected one component node but found more.");
299                         }
300                         if (components.size() == 1) {
301                             contextObjects.put(ATTRIBUTE_COMPONENT, components.get(0));
302                         } else {
303                             contextObjects.put(ATTRIBUTE_COMPONENT, null);
304                         }
305                     } else {
306                         contextObjects.put(ATTRIBUTE_COMPONENTS, components);
307                     }
308                     // FIXME we shouldn't manipulate the area definition directly
309                     // we should use merge with the proxy approach
310                     if (areaDefinition instanceof ConfiguredAreaDefinition) {
311                         if (areaDefinition.getTemplateScript() == null) {
312                             ((ConfiguredAreaDefinition) areaDefinition).setRenderType(NoScriptRenderer.NO_SCRIPT_RENDERER);
313                         } else if (areaDefinition.getRenderType() == null) {
314                             ((ConfiguredAreaDefinition) areaDefinition).setRenderType(this.templateDefinition.getRenderType());
315                         }
316 
317                         if (areaDefinition.getI18nBasename() == null) {
318                             ((ConfiguredAreaDefinition) areaDefinition).setI18nBasename(this.templateDefinition.getI18nBasename());
319                         }
320                     }
321 
322                     WebContext webContext = MgnlContext.getWebContext();
323                     webContext.push(webContext.getRequest(), webContext.getResponse());
324                     setAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
325                     try {
326                         AppendableOnlyOutputProvider appendable = new AppendableOnlyOutputProvider(out);
327                         renderingEngine.render(areaNode, areaDefinition, contextObjects, appendable);
328                     } finally {
329                         webContext.pop();
330                         webContext.setPageContext(null);
331                         restoreAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
332                     }
333                 }
334             }
335             if (isAdmin() && this.isAreaDefinitionEnabled) {
336                 MarkupHelper helper = new MarkupHelper(out);
337                 helper.closeComment(CMS_AREA);
338             }
339 
340         } catch (Exception e) {
341             throw new RenderException("Can't render area " + areaNode + " with name " + this.name, e);
342         }
343     }
344 
345     protected Node tryToCreateAreaNode(Node parentNode) throws RenderException {
346         Node area = null;
347         try {
348             if (parentNode.hasNode(name)) {
349                 area = parentNode.getNode(name);
350             } else {
351                 // autocreate and save area only if it's not optional
352                 if (!this.optional) {
353                     area = createNewAreaNode(parentNode);
354                 }
355             }
356         } catch (RepositoryException e) {
357             throw new RenderException("Can't access or create area node [" + name + "] on [" + parentNode + "]: " + e.getMessage(), e);
358         }
359         // at this stage we can be sure that the target area, unless optional, has been created.
360         if (area != null) {
361             // TODO fgrilli: what about other component types to be autogenerated (i.e. autogenerating an entire page)?
362             final AutoGenerationConfiguration autoGeneration = areaDefinition.getAutoGeneration();
363             if (autoGeneration != null && autoGeneration.getGeneratorClass() != null) {
364                 try {
365                     final String areaId = area.getIdentifier();
366                     final String workspaceName = area.getSession().getWorkspace().getName();
367                     MgnlContext.doInSystemContext(new MgnlContext.Op<Void, RepositoryException>() {
368                         @Override
369                         public Void exec() throws RepositoryException {
370                             Node areaNodeInSystemSession = NodeUtil.getNodeByIdentifier(workspaceName, areaId);
371                             try {
372                                 Components.newInstance(autoGeneration.getGeneratorClass(), areaNodeInSystemSession).generate(autoGeneration);
373                             } catch (RenderException e) {
374                                 log.error("Can't render autogenerated area '{}'.", areaNodeInSystemSession);
375                             }
376                             return null;
377                         }
378                     });
379                 } catch (RepositoryException e) {
380                     log.error("Can't autocreate area '{}'.", area);
381                 }
382             }
383         }
384         return area;
385     }
386 
387     protected AreaDefinition resolveAreaDefinition() {
388         if (areaDefinition != null) {
389             return areaDefinition;
390         }
391 
392         if (!StringUtils.isEmpty(name)) {
393             if (templateDefinition != null && templateDefinition.getAreas().containsKey(name)) {
394                 return templateDefinition.getAreas().get(name);
395             }
396         }
397         // happens if no area definition is passed or configured
398         // an ad-hoc area definition will be created
399         return null;
400     }
401 
402     protected TemplateDefinition resolveTemplateDefinition() throws RenderException {
403         final RenderableDefinition renderableDefinition = getRenderingContext().getRenderableDefinition();
404         if (renderableDefinition == null || renderableDefinition instanceof TemplateDefinition) {
405             return (TemplateDefinition) renderableDefinition;
406         }
407         throw new RenderException("Current RenderableDefinition [" + renderableDefinition + "] is not of type TemplateDefinition. Areas cannot be supported");
408     }
409 
410     /*
411      * An area script can be rendered when
412      * area is enabled
413      *
414      * AND
415      *
416      * If an area is optional:
417      *
418      * if not yet created the area bar has a create button and the script is
419      * - executed in the edit mode but the content object is null (otherwise we can't place the bar)
420      * - not executed otherwise (no place holder divs)
421      *
422      * If created, the bar has a remove button (other areas cannot be removed nor created)
423      *
424      * If an area is required:
425      *
426      * the area node gets created (always) the script is always executed.
427      */
428     private boolean canRenderAreaScript() {
429         // FYI: areaDefinition == null when it is not set explicitly and can't be merged with the parent. In such case we will render it as if it was enabled
430         return this.isAreaDefinitionEnabled && (areaNode != null || areaNode == null && this.optional && !MgnlContext.getAggregationState().isPreviewMode());
431     }
432 
433     private String resolveDialog() {
434         return dialog != null ? dialog : areaDefinition != null ? areaDefinition.getDialog() : null;
435     }
436 
437     private String resolveType() {
438         return type != null ? type : areaDefinition != null && areaDefinition.getType() != null ? areaDefinition.getType() : AreaDefinition.DEFAULT_TYPE;
439     }
440 
441     private String resolveName() {
442         return name != null ? name : areaDefinition != null ? areaDefinition.getName() : null;
443     }
444 
445     private String resolveLabel() {
446         return label != null ? label : areaDefinition != null && StringUtils.isNotBlank(areaDefinition.getTitle()) ? areaDefinition.getTitle() : StringUtils.capitalize(name);
447     }
448 
449     private Boolean resolveOptional() {
450         return optional != null ? optional : areaDefinition != null && areaDefinition.getOptional() != null ? areaDefinition.getOptional() : Boolean.FALSE;
451     }
452 
453     private Boolean resolveEditable() {
454         return editable != null ? editable : areaDefinition != null && areaDefinition.getEditable() != null ? areaDefinition.getEditable() : null;
455     }
456 
457     private Integer resolveMaximumOfComponents() {
458         return maxComponents != null ? maxComponents : areaDefinition != null && areaDefinition.getMaxComponents() != null ? areaDefinition.getMaxComponents() : Integer.MAX_VALUE;
459     }
460 
461     private boolean isInheritanceEnabled() {
462         return areaDefinition != null && areaDefinition.getInheritance() != null && areaDefinition.getInheritance().isEnabled() != null && areaDefinition.getInheritance().isEnabled();
463     }
464 
465     private boolean isOptionalAreaCreated() {
466         return this.optional && this.areaNode != null;
467     }
468 
469     private boolean hasComponents(Node parent) throws RenderException {
470         try {
471             return NodeUtil.getNodes(parent, MgnlNodeType.NT_COMPONENT).iterator().hasNext();
472         } catch (RepositoryException e) {
473             throw new RenderException(e);
474         }
475     }
476 
477     private int numberOfComponents(Node parent) throws RenderException {
478         try {
479             return NodeUtil.asList(NodeUtil.getNodes(parent, MgnlNodeType.NT_COMPONENT)).size();
480         } catch (RepositoryException e) {
481             throw new RenderException(e);
482         }
483     }
484 
485     protected String resolveAvailableComponents() {
486         if (StringUtils.isNotEmpty(availableComponents)) {
487             return StringUtils.remove(availableComponents, " ");
488         }
489         if (areaDefinition != null && areaDefinition.getAvailableComponents().size() > 0) {
490             Iterator<ComponentAvailability> iterator = areaDefinition.getAvailableComponents().values().iterator();
491             List<String> componentIds = new ArrayList<String>();
492             final Collection<String> userRoles = MgnlContext.getUser().getAllRoles();
493             while (iterator.hasNext()) {
494                 ComponentAvailability availableComponent = iterator.next();
495                 if (availableComponent.isEnabled()) {
496                     // check roles
497                     final Collection<String> roles = availableComponent.getRoles();
498                     if (!roles.isEmpty()) {
499                         if (CollectionUtils.containsAny(userRoles, roles)) {
500                             componentIds.add(availableComponent.getId());
501                         }
502                     } else {
503                         componentIds.add(availableComponent.getId());
504                     }
505                 }
506             }
507             return StringUtils.join(componentIds, ',');
508         }
509         return "";
510     }
511 
512     private boolean shouldShowAddButton() throws RenderException {
513 
514         if (areaNode == null || type.equals(AreaDefinition.TYPE_NO_COMPONENT)) {
515             return false;
516         }
517 
518         int numberOfComponents = numberOfComponents(areaNode);
519         if (numberOfComponents >= maxComponents || numberOfComponents > 0 && type.equals(AreaDefinition.TYPE_SINGLE)) {
520             return false;
521         }
522 
523         return true;
524     }
525 
526     private boolean shouldShowNewComponentArea() throws RenderException {
527 
528         if (areaNode == null || type.equals(AreaDefinition.TYPE_NO_COMPONENT) || type.equals(AreaDefinition.TYPE_SINGLE) && hasComponents(areaNode)) {
529             return false;
530         }
531         return true;
532     }
533 
534     public String getName() {
535         return name;
536     }
537 
538     public void setName(String name) {
539         this.name = name;
540     }
541 
542     public AreaDefinition getArea() {
543         return areaDefinition;
544     }
545 
546     public void setArea(AreaDefinition area) {
547         this.areaDefinition = area;
548     }
549 
550     public String getAvailableComponents() {
551         return availableComponents;
552     }
553 
554     public void setAvailableComponents(String availableComponents) {
555         this.availableComponents = availableComponents;
556     }
557 
558     public String getType() {
559         return type;
560     }
561 
562     public void setType(String type) {
563         this.type = type;
564     }
565 
566     public String getDialog() {
567         return dialog;
568     }
569 
570     public void setDialog(String dialog) {
571         this.dialog = dialog;
572     }
573 
574     public String getLabel() {
575         return label;
576     }
577 
578     public void setLabel(String label) {
579         this.label = label;
580     }
581 
582     public String getDescription() {
583         return description;
584     }
585 
586     public void setDescription(String description) {
587         this.description = description;
588     }
589 
590     public boolean isInherit() {
591         return inherit;
592     }
593 
594     public void setInherit(boolean inherit) {
595         this.inherit = inherit;
596     }
597 
598     public Boolean getEditable() {
599         return editable;
600     }
601 
602     public void setEditable(Boolean editable) {
603         this.editable = editable;
604     }
605 
606     public Map<String, Object> getContextAttributes() {
607         return contextAttributes;
608     }
609 
610     public void setContextAttributes(Map<String, Object> contextAttributes) {
611         this.contextAttributes = contextAttributes;
612     }
613 
614     public Integer getMaxComponents() {
615         return maxComponents;
616     }
617 
618     public void setMaxComponents(Integer maxComponents) {
619         this.maxComponents = maxComponents;
620     }
621 }