View Javadoc
1   /**
2    * This file Copyright (c) 2012-2016 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.i18n.Messages;
38  import info.magnolia.cms.i18n.MessagesManager;
39  import info.magnolia.cms.security.User;
40  import info.magnolia.cms.security.operations.OperationPermissionDefinition;
41  import info.magnolia.context.MgnlContext;
42  import info.magnolia.context.WebContext;
43  import info.magnolia.jcr.inheritance.InheritanceNodeWrapper;
44  import info.magnolia.registry.RegistrationException;
45  import info.magnolia.rendering.context.RenderingContext;
46  import info.magnolia.rendering.engine.AppendableOnlyOutputProvider;
47  import info.magnolia.rendering.engine.RenderException;
48  import info.magnolia.rendering.engine.RenderingEngine;
49  import info.magnolia.rendering.template.AreaDefinition;
50  import info.magnolia.rendering.template.ComponentAvailability;
51  import info.magnolia.rendering.template.TemplateDefinition;
52  import info.magnolia.rendering.template.assignment.TemplateDefinitionAssignment;
53  import info.magnolia.templating.freemarker.AreaDirective;
54  
55  import java.io.IOException;
56  import java.util.HashMap;
57  import java.util.Iterator;
58  import java.util.Map;
59  
60  import javax.inject.Inject;
61  import javax.jcr.Node;
62  import javax.jcr.RepositoryException;
63  import javax.jcr.Session;
64  
65  import org.apache.commons.lang3.StringUtils;
66  import org.slf4j.Logger;
67  import org.slf4j.LoggerFactory;
68  
69  /**
70   * Renders a piece of content.
71   */
72  public class ComponentElement extends AbstractContentTemplatingElement {
73  
74      private static final Logger log = LoggerFactory.getLogger(ComponentElement.class);
75  
76      private Map<String, Object> contextAttributes = new HashMap<String, Object>();
77      private final RenderingEngine renderingEngine;
78      private Node content;
79      private final TemplateDefinitionAssignment templateDefinitionAssignment;
80      private TemplateDefinition componentDefinition;
81  
82      private boolean renderEditbar = true;
83      private String dialog;
84      private Boolean editable;
85      private Boolean moveable, writable, deletable;
86  
87      @Inject
88      public ComponentElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine, TemplateDefinitionAssignment templateDefinitionAssignment) {
89          super(server, renderingContext);
90          this.renderingEngine = renderingEngine;
91          this.templateDefinitionAssignment = templateDefinitionAssignment;
92      }
93  
94      @Override
95      public void begin(Appendable out) throws IOException, RenderException {
96  
97          content = getPassedContent();
98  
99          if (content == null) {
100             throw new RenderException("The 'content' or 'workspace' and 'path' attribute have to be set to render a component.");
101         }
102 
103         if (renderComments()) { // add condition into renderComments() method when adding extra condition to make sure it's in sync with adding comments in end() method
104 
105             try {
106                 this.componentDefinition = templateDefinitionAssignment.getAssignedTemplateDefinition(content);
107             } catch (RegistrationException e) {
108                 throw new RenderException("No template definition found for the current content", e);
109             }
110 
111             final Messages messages = MessagesManager.getMessages(componentDefinition.getI18nBasename());
112 
113             MarkupHelper helper = new MarkupHelper(out);
114 
115             helper.openComment("cms:component");
116 
117             helper.attribute(AreaDirective.CONTENT_ATTRIBUTE, getNodePath(content));
118 
119             if (content instanceof InheritanceNodeWrapper) {
120                 if (((InheritanceNodeWrapper) content).isInherited()) {
121                     helper.attribute("inherited", "true");
122                 }
123             }
124 
125             this.editable = resolveEditable();
126             if (this.editable != null) {
127                 helper.attribute("editable", String.valueOf(this.editable));
128             }
129 
130             final AreaDefinition areaDefinition = this.getRenderingContext().getParentAreaDefinition();
131             OperationPermissionDefinition permissions = null;
132             User user = null;
133 
134             if (areaDefinition != null) {
135                 String componentId = componentDefinition.getId();
136                 ComponentAvailability componentAvailability = null;
137                 Iterator<ComponentAvailability> iterator = areaDefinition.getAvailableComponents().values().iterator();
138                 while (iterator.hasNext()) {
139                     ComponentAvailability availability = iterator.next();
140                     if (availability.getId().equals(componentId)) {
141                         componentAvailability = availability;
142                         break;
143                     }
144                 }
145                 if (componentAvailability != null && componentAvailability.getPermissions() != null) {
146                     permissions = componentAvailability.getPermissions();
147                     user = MgnlContext.getUser();
148                 }
149             }
150 
151             this.moveable = this.resolveMoveable(permissions, user);
152             if (this.moveable != null) {
153                 helper.attribute(OperationPermissionDefinition.MOVEABLE, String.valueOf(this.moveable));
154             }
155 
156             this.writable = this.resolveWritable(permissions, user);
157             if (this.writable != null) {
158                 helper.attribute(OperationPermissionDefinition.WRITABLE, String.valueOf(this.writable));
159             }
160 
161             this.deletable = this.resolveDeletable(permissions, user);
162             if (this.deletable != null) {
163                 helper.attribute(OperationPermissionDefinition.DELETABLE, String.valueOf(this.deletable));
164             }
165 
166             if (StringUtils.isEmpty(dialog)) {
167                 dialog = resolveDialog();
168             }
169             helper.attribute("dialog", dialog);
170 
171             String label = StringUtils.defaultIfEmpty(componentDefinition.getTitle(), componentDefinition.getName());
172             helper.attribute("label", messages.getWithDefault(label, label));
173 
174             if (StringUtils.isNotEmpty(componentDefinition.getDescription())) {
175                 helper.attribute("description", componentDefinition.getDescription());
176             }
177             helper.append(" -->\n");
178         }
179 
180         // TODO not sure how to pass editable
181 
182         WebContext webContext = MgnlContext.getWebContext();
183         webContext.push(webContext.getRequest(), webContext.getResponse());
184         setAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
185 
186         try {
187             if (componentDefinition != null) {
188                 renderingEngine.render(content, componentDefinition, new HashMap<String, Object>(), new AppendableOnlyOutputProvider(out));
189             } else {
190                 renderingEngine.render(content, new AppendableOnlyOutputProvider(out));
191             }
192         } finally {
193             webContext.pop();
194             webContext.setPageContext(null);
195             restoreAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
196         }
197     }
198 
199     private boolean hasPermission(Node node) {
200         try {
201             return node.getSession().hasPermission(node.getPath(), Session.ACTION_SET_PROPERTY);
202         } catch (RepositoryException e) {
203             log.error("Could not determine permission for node {}", node);
204         }
205         return false;
206     }
207 
208     private Boolean resolveEditable() {
209         return editable != null ? editable : componentDefinition != null && componentDefinition.getEditable() != null ? componentDefinition.getEditable() : null;
210     }
211 
212     private Boolean resolveMoveable(final OperationPermissionDefinition permissions, User user) {
213 
214         Boolean moveable = this.moveable != null ? this.moveable : componentDefinition != null && componentDefinition.getMoveable() != null ? componentDefinition.getMoveable() : null;
215         if (moveable != null || permissions == null) {
216             return moveable;
217         }
218 
219         // try to get the permissions from template availability
220         if (!permissions.canMove(user)) {
221             return false;
222         }
223         return true; // true by default
224     }
225 
226     private Boolean resolveWritable(final OperationPermissionDefinition permissions, User user) {
227 
228         Boolean writable = this.writable != null ? this.writable : componentDefinition != null && componentDefinition.getWritable() != null ? componentDefinition.getWritable() : null;
229         if (writable != null || permissions == null) {
230             return writable;
231         }
232         // try to get the permissions from template availability
233         if (!permissions.canWrite(user)) {
234             return false;
235         }
236         return true; // true by default
237     }
238 
239     private Boolean resolveDeletable(final OperationPermissionDefinition permissions, User user) {
240 
241         Boolean deletable = this.deletable != null ? this.deletable : componentDefinition != null && componentDefinition.getDeletable() != null ? componentDefinition.getDeletable() : null;
242         if (deletable != null || permissions == null) {
243             return deletable;
244         }
245         // try to get the permissions from template availability
246         if (!permissions.canDelete(user)) {
247             return false;
248         }
249         return true; // true by default
250     }
251 
252     @Override
253     public void end(Appendable out) throws IOException, RenderException {
254         if (renderComments()) { // add condition into renderComments() method when adding extra condition to make sure it's in sync with adding comments in begin() method
255             new MarkupHelper(out).closeComment("cms:component");
256         }
257     }
258 
259     public Map<String, Object> getContextAttributes() {
260         return contextAttributes;
261     }
262 
263     public void setContextAttributes(Map<String, Object> contextAttributes) {
264         this.contextAttributes = contextAttributes;
265     }
266 
267     private String resolveDialog() {
268         if (StringUtils.isNotEmpty(this.dialog)) {
269             return this.dialog;
270         }
271         String dialog = componentDefinition.getDialog();
272         if (StringUtils.isNotEmpty(dialog)) {
273             return dialog;
274         }
275         return null;
276     }
277 
278     public void setDialog(String dialog) {
279         this.dialog = dialog;
280     }
281 
282     public void setEditable(Boolean editable) {
283         this.editable = editable;
284     }
285 
286     public Boolean getEditable() {
287         return editable;
288     }
289 
290     public boolean isRenderEditbar() {
291         return renderEditbar;
292     }
293 
294     public void setRenderEditbar(boolean renderEditbar) {
295         this.renderEditbar = renderEditbar;
296     }
297 
298     @Override
299     protected boolean renderComments() {
300         return this.renderEditbar && isAdmin() && !MgnlContext.getAggregationState().isPreviewMode() && hasPermission(this.content);
301     }
302 }