View Javadoc

1   /**
2    * This file Copyright (c) 2011-2012 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.MgnlNodeType;
38  import info.magnolia.cms.i18n.Messages;
39  import info.magnolia.cms.i18n.MessagesManager;
40  import info.magnolia.context.MgnlContext;
41  import info.magnolia.context.WebContext;
42  import info.magnolia.jcr.RuntimeRepositoryException;
43  import info.magnolia.jcr.util.ContentMap;
44  import info.magnolia.jcr.util.NodeUtil;
45  import info.magnolia.objectfactory.Components;
46  import info.magnolia.rendering.context.RenderingContext;
47  import info.magnolia.rendering.engine.AppendableOnlyOutputProvider;
48  import info.magnolia.rendering.engine.RenderException;
49  import info.magnolia.rendering.engine.RenderingEngine;
50  import info.magnolia.rendering.generator.Generator;
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  
60  import java.io.IOException;
61  import java.util.ArrayList;
62  import java.util.Collection;
63  import java.util.HashMap;
64  import java.util.Iterator;
65  import java.util.List;
66  import java.util.Map;
67  
68  import javax.jcr.Node;
69  import javax.jcr.RepositoryException;
70  import javax.jcr.Session;
71  
72  import org.apache.commons.collections.CollectionUtils;
73  import org.apache.commons.lang.StringUtils;
74  import org.slf4j.Logger;
75  import org.slf4j.LoggerFactory;
76  
77  
78  /**
79   * Renders an area and outputs a marker that instructs the page editor to place a bar at this location.
80   *
81   * @version $Id$
82   */
83  public class AreaElement extends AbstractContentTemplatingElement {
84  
85      private static final Logger log = LoggerFactory.getLogger(AreaElement.class);
86      public static final String CMS_AREA = "cms:area";
87  
88      public static final String ATTRIBUTE_COMPONENT = "component";
89      public static final String ATTRIBUTE_COMPONENTS = "components";
90  
91      private final RenderingEngine renderingEngine;
92  
93      private Node areaNode;
94      private TemplateDefinition templateDefinition;
95      private AreaDefinition areaDefinition;
96      private String name;
97      private String type;
98      private String dialog;
99      private String availableComponents;
100     private String label;
101     private String description;
102     private Boolean inherit;
103     private Boolean optional;
104     private Boolean editable;
105 
106     private Map<String, Object> contextAttributes = new HashMap<String, Object>();
107 
108     private String areaPath;
109 
110     private boolean isAreaDefinitionEnabled;
111 
112 
113     public AreaElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine) {
114         super(server, renderingContext);
115         this.renderingEngine = renderingEngine;
116     }
117 
118     @Override
119     public void begin(Appendable out) throws IOException, RenderException {
120 
121         this.templateDefinition = resolveTemplateDefinition();
122         Messages messages = MessagesManager.getMessages(templateDefinition.getI18nBasename());
123 
124         this.areaDefinition = resolveAreaDefinition();
125 
126         this.isAreaDefinitionEnabled = areaDefinition != null && (areaDefinition.isEnabled() == null || areaDefinition.isEnabled());
127 
128         if (!this.isAreaDefinitionEnabled) {
129             return;
130         }
131         // set the values based on the area definition if not passed
132         this.name = resolveName();
133         this.dialog = resolveDialog();
134         this.type = resolveType();
135         this.label = resolveLabel();
136         this.availableComponents = resolveAvailableComponents();
137         this.inherit = isInheritanceEnabled();
138         this.optional = resolveOptional();
139         this.editable = resolveEditable();
140 
141         this.description = templateDefinition.getDescription();
142 
143         // build an adhoc area definition if no area definition can be resolved
144         if(this.areaDefinition == null){
145             buildAdHocAreaDefinition();
146         }
147 
148         // read area node and calculate the area path
149         this.areaNode = getPassedContent();
150         if(this.areaNode != null){
151             this.areaPath = getNodePath(areaNode);
152         }
153         else {
154             // will be null if no area has been created (for instance for optional areas)
155             // current content is the parent node
156             Node parentNode = currentContent();
157             this.areaNode = tryToCreateAreaNode(parentNode);
158             this.areaPath = getNodePath(parentNode) + "/" + name;
159         }
160 
161         if (isAdmin() && hasPermission(this.areaNode)) {
162             MarkupHelper helper = new MarkupHelper(out);
163 
164             helper.openComment(CMS_AREA).attribute(AbstractDirective.CONTENT_ATTRIBUTE, this.areaPath);
165             helper.attribute("name", this.name);
166             helper.attribute("availableComponents", this.availableComponents);
167             helper.attribute("type", this.type);
168             helper.attribute("dialog", this.dialog);
169             helper.attribute("label", messages.getWithDefault(this.label, this.label));
170             helper.attribute("inherit", String.valueOf(this.inherit));
171             if (this.editable != null) {
172                 helper.attribute("editable", String.valueOf(this.editable));
173             }
174             helper.attribute("optional", String.valueOf(this.optional));
175             if(isOptionalAreaCreated()) {
176                 helper.attribute("created", "true");
177             }
178             helper.attribute("showAddButton", String.valueOf(shouldShowAddButton()));
179             if (StringUtils.isNotBlank(description)) {
180                 helper.attribute("description", messages.getWithDefault(description, description));
181             }
182 
183             helper.append(" -->\n");
184 
185         }
186     }
187 
188     private boolean hasPermission(Node node) {
189         if (node == null) {
190             node = currentContent();
191         }
192         try {
193             return node.getSession().hasPermission(node.getPath(), Session.ACTION_SET_PROPERTY);
194         } catch (RepositoryException e) {
195             log.error("Could not determine permission for node {}", node);
196         }
197         return false;
198     }
199 
200     private Node createNewAreaNode(Node parentNode) throws RepositoryException {
201         final String parentId = parentNode.getIdentifier();
202         final String workspaceName = parentNode.getSession().getWorkspace().getName();
203         try {
204             MgnlContext.doInSystemContext(new MgnlContext.Op<Void, RepositoryException>() {
205                 @Override
206                 public Void exec() throws RepositoryException {
207                     Node parentNodeInSystemSession = NodeUtil.getNodeByIdentifier(workspaceName, parentId);
208                     Node newAreaNode = NodeUtil.createPath(parentNodeInSystemSession, AreaElement.this.name, MgnlNodeType.NT_AREA);
209                     newAreaNode.getSession().save();
210                     return null;
211                 }
212             });
213         } catch (RepositoryException e) {
214             log.error("ignoring problem w/ creating area in workspace {} for node {}", workspaceName, parentId);
215             // ignore, when working w/ versioned nodes ...
216             return null;
217         }
218         return parentNode.getNode(this.name);
219     }
220 
221     protected void buildAdHocAreaDefinition() {
222         ConfiguredAreaDefinition addHocAreaDefinition = new ConfiguredAreaDefinition();
223         addHocAreaDefinition.setName(this.name);
224         addHocAreaDefinition.setDialog(this.dialog);
225         addHocAreaDefinition.setType(this.type);
226         addHocAreaDefinition.setRenderType(this.templateDefinition.getRenderType());
227         areaDefinition = addHocAreaDefinition;
228     }
229 
230     @Override
231     public void end(Appendable out) throws RenderException {
232 
233         try {
234             if (canRenderAreaScript()) {
235                 if(isInherit() && areaNode != null) {
236                     try {
237                         areaNode = new DefaultInheritanceContentDecorator(areaNode, areaDefinition.getInheritance()).wrapNode(areaNode);
238                     } catch (RepositoryException e) {
239                         throw new RuntimeRepositoryException(e);
240                     }
241                 }
242                 Map<String, Object> contextObjects = new HashMap<String, Object>();
243 
244                 List<ContentMap> components = new ArrayList<ContentMap>();
245 
246                 if (areaNode != null) {
247                     for (Node node : NodeUtil.getNodes(areaNode, MgnlNodeType.NT_COMPONENT)) {
248                         components.add(new ContentMap(node));
249                     }
250                 }
251                 if(AreaDefinition.TYPE_SINGLE.equals(type)) {
252                     if(components.size() > 1) {
253                         throw new RenderException("Can't render single area [" + areaNode + "]: expected one component node but found more.");
254                     }
255                     if(components.size() == 1) {
256                         contextObjects.put(ATTRIBUTE_COMPONENT, components.get(0));
257                     } else {
258                         contextObjects.put(ATTRIBUTE_COMPONENT, null);
259                     }
260                 } else {
261                     contextObjects.put(ATTRIBUTE_COMPONENTS, components);
262                 }
263                 // FIXME we shouldn't manipulate the area definition directly
264                 // we should use merge with the proxy approach
265                 if(areaDefinition.getRenderType() == null && areaDefinition instanceof ConfiguredAreaDefinition){
266                     ((ConfiguredAreaDefinition)areaDefinition).setRenderType(this.templateDefinition.getRenderType());
267                 }
268 
269                 // FIXME we shouldn't manipulate the area definition directly
270                 // we should use merge with the proxy approach
271                 if(areaDefinition.getI18nBasename() == null && areaDefinition instanceof ConfiguredAreaDefinition){
272                     ((ConfiguredAreaDefinition)areaDefinition).setI18nBasename(this.templateDefinition.getI18nBasename());
273                 }
274                 WebContext webContext = MgnlContext.getWebContext();
275                 webContext.push(webContext.getRequest(), webContext.getResponse());
276                 setAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
277                 try {
278                     AppendableOnlyOutputProvider appendable = new AppendableOnlyOutputProvider(out);
279                     if(StringUtils.isNotEmpty(areaDefinition.getTemplateScript())){
280                         renderingEngine.render(areaNode, areaDefinition, contextObjects, appendable);
281                     }
282                     // no script
283                     else{
284                         for (ContentMap component : components) {
285                             ComponentElement componentElement = Components.newInstance(ComponentElement.class);
286                             componentElement.setContent(component.getJCRNode());
287                             componentElement.begin(out);
288                             componentElement.end(out);
289                         }
290                     }
291                 } finally {
292                     webContext.pop();
293                     webContext.setPageContext(null);
294                     restoreAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
295                 }
296 
297             }
298 
299             if (isAdmin() && this.isAreaDefinitionEnabled) {
300                 MarkupHelper helper = new MarkupHelper(out);
301                 helper.closeComment(CMS_AREA);
302             }
303         } catch (Exception e) {
304             throw new RenderException("Can't render area " + areaNode + " with name " + this.name, e);
305         }
306     }
307 
308     protected Node tryToCreateAreaNode(Node parentNode) throws RenderException {
309         Node area = null;
310         try {
311             if(parentNode.hasNode(name)){
312                 area = parentNode.getNode(name);
313             } else {
314                 //autocreate and save area only if it's not optional
315                 if(!this.optional) {
316                     area = createNewAreaNode(parentNode);
317                 }
318             }
319         }
320         catch (RepositoryException e) {
321             throw new RenderException("Can't access area node [" + name + "] on [" + parentNode + "]", e);
322         }
323         //at this stage we can be sure that the target area, unless optional, has been created.
324         if(area != null) {
325             //TODO fgrilli: what about other component types to be autogenerated (i.e. autogenerating an entire page)?
326             final AutoGenerationConfiguration autoGeneration = areaDefinition.getAutoGeneration();
327             if (autoGeneration != null && autoGeneration.getGeneratorClass() != null) {
328                 ((Generator<AutoGenerationConfiguration>) Components.newInstance(autoGeneration.getGeneratorClass(), area)).generate(autoGeneration);
329             }
330         }
331         return area;
332     }
333 
334     protected AreaDefinition resolveAreaDefinition() {
335         if (areaDefinition != null) {
336             return areaDefinition;
337         }
338 
339         if (!StringUtils.isEmpty(name)) {
340             if (templateDefinition != null && templateDefinition.getAreas().containsKey(name)) {
341                 return templateDefinition.getAreas().get(name);
342             }
343         }
344         // happens if no area definition is passed or configured
345         // an ad-hoc area definition will be created
346         return null;
347     }
348 
349     protected TemplateDefinition resolveTemplateDefinition() throws RenderException {
350         final RenderableDefinition renderableDefinition = getRenderingContext().getRenderableDefinition();
351         if (renderableDefinition == null || renderableDefinition instanceof TemplateDefinition) {
352             return (TemplateDefinition) renderableDefinition;
353         }
354         throw new RenderException("Current RenderableDefinition [" + renderableDefinition + "] is not of type TemplateDefinition. Areas cannot be supported");
355     }
356 
357     /*
358      * An area script can be rendered when
359      * area is enabled
360      *
361      * AND
362      *
363      * If an area is optional:
364      *
365      * if not yet created the area bar has a create button and the script is
366      * - executed in the edit mode but the content object is null (otherwise we can't place the bar)
367      * - not executed otherwise (no place holder divs)
368      *
369      * If created, the bar has a remove button (other areas cannot be removed nor created)
370      *
371      * If an area is required:
372      *
373      * the area node gets created (always) the script is always executed.
374      */
375     private boolean canRenderAreaScript() {
376         // 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
377         return this.isAreaDefinitionEnabled && (areaNode != null || (areaNode == null && areaDefinition.isOptional() && !MgnlContext.getAggregationState().isPreviewMode()));
378     }
379 
380     private String resolveDialog() {
381         return dialog != null ? dialog : areaDefinition != null ? areaDefinition.getDialog() : null;
382     }
383 
384     private String resolveType() {
385         return type != null ? type : areaDefinition != null && areaDefinition.getType() != null ? areaDefinition.getType() : AreaDefinition.DEFAULT_TYPE;
386     }
387 
388     private String resolveName() {
389         return name != null ? name : (areaDefinition != null ? areaDefinition.getName() : null);
390     }
391 
392     private String resolveLabel() {
393         return label != null ? label : (areaDefinition != null && StringUtils.isNotBlank(areaDefinition.getTitle()) ? areaDefinition.getTitle() : StringUtils.capitalize(name));
394     }
395 
396     private Boolean resolveOptional() {
397         return optional != null ? optional : areaDefinition != null && areaDefinition.isOptional() != null ? areaDefinition.isOptional() : Boolean.FALSE;
398     }
399 
400     private Boolean resolveEditable() {
401         return editable != null ? editable : areaDefinition != null && areaDefinition.getEditable() != null ? areaDefinition.getEditable() : null;
402     }
403 
404     private boolean isInheritanceEnabled() {
405         return areaDefinition != null && areaDefinition.getInheritance() != null && areaDefinition.getInheritance().isEnabled() != null && areaDefinition.getInheritance().isEnabled();
406     }
407 
408     private boolean isOptionalAreaCreated() {
409         return this.optional && this.areaNode != null;
410     }
411 
412     private boolean hasComponents(Node parent) throws RenderException {
413         try {
414             return NodeUtil.getNodes(parent, MgnlNodeType.NT_COMPONENT).iterator().hasNext();
415         } catch (RepositoryException e) {
416             throw new RenderException(e);
417         }
418     }
419 
420     protected String resolveAvailableComponents() {
421         if (StringUtils.isNotEmpty(availableComponents)) {
422             return StringUtils.remove(availableComponents, " ");
423         }
424         if (areaDefinition != null && areaDefinition.getAvailableComponents().size() > 0) {
425             Iterator<ComponentAvailability> iterator = areaDefinition.getAvailableComponents().values().iterator();
426             List<String> componentIds = new ArrayList<String>();
427             final Collection<String> userRoles = MgnlContext.getUser().getAllRoles();
428             while (iterator.hasNext()) {
429                 ComponentAvailability availableComponent = iterator.next();
430                 if(availableComponent.isEnabled()) {
431                     // check roles
432                     final Collection<String> roles = availableComponent.getRoles();
433                     if (!roles.isEmpty()) {
434                         if (CollectionUtils.containsAny(userRoles, roles)) {
435                             componentIds.add(availableComponent.getId());
436                         }
437                     } else {
438                         componentIds.add(availableComponent.getId());
439                     }
440                 }
441             }
442             return StringUtils.join(componentIds, ',');
443         }
444         return "";
445     }
446 
447     private boolean shouldShowAddButton() throws RenderException {
448 
449         if(areaNode == null || type.equals(AreaDefinition.TYPE_NO_COMPONENT) || (type.equals(AreaDefinition.TYPE_SINGLE) && hasComponents(areaNode))) {
450             return false;
451         }
452 
453         return true;
454     }
455 
456     public String getName() {
457         return name;
458     }
459 
460     public void setName(String name) {
461         this.name = name;
462     }
463 
464     public AreaDefinition getArea() {
465         return areaDefinition;
466     }
467 
468     public void setArea(AreaDefinition area) {
469         this.areaDefinition = area;
470     }
471 
472     public String getAvailableComponents() {
473         return availableComponents;
474     }
475 
476     public void setAvailableComponents(String availableComponents) {
477         this.availableComponents = availableComponents;
478     }
479 
480     public String getType() {
481         return type;
482     }
483 
484     public void setType(String type) {
485         this.type = type;
486     }
487 
488     public String getDialog() {
489         return dialog;
490     }
491 
492     public void setDialog(String dialog) {
493         this.dialog = dialog;
494     }
495 
496     public String getLabel() {
497         return label;
498     }
499 
500     public void setLabel(String label) {
501         this.label = label;
502     }
503 
504     public String getDescription() {
505         return description;
506     }
507 
508     public void setDescription(String description) {
509         this.description = description;
510     }
511 
512     public boolean isInherit() {
513         return inherit;
514     }
515 
516     public void setInherit(boolean inherit) {
517         this.inherit = inherit;
518     }
519 
520     public Boolean getEditable() {
521         return editable;
522     }
523 
524     public void setEditable(Boolean editable) {
525         this.editable = editable;
526     }
527 
528     public Map<String, Object> getContextAttributes() {
529         return contextAttributes;
530     }
531 
532     public void setContextAttributes(Map<String, Object> contextAttributes) {
533         this.contextAttributes = contextAttributes;
534     }
535 }