1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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.context.MgnlContext;
40 import info.magnolia.context.WebContext;
41 import info.magnolia.jcr.RuntimeRepositoryException;
42 import info.magnolia.jcr.util.ContentMap;
43 import info.magnolia.jcr.util.NodeTypes;
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.rendering.template.variation.RenderableVariationResolver;
58 import info.magnolia.templating.freemarker.AbstractDirective;
59 import info.magnolia.templating.inheritance.DefaultInheritanceContentDecorator;
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.inject.Inject;
70 import javax.jcr.Node;
71 import javax.jcr.PathNotFoundException;
72 import javax.jcr.RepositoryException;
73 import javax.jcr.Session;
74 import javax.jcr.lock.LockException;
75
76 import org.apache.commons.collections.CollectionUtils;
77 import org.apache.commons.lang.StringUtils;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81
82
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 private final RenderingEngine renderingEngine;
93
94 private Node areaNode;
95 private TemplateDefinition templateDefinition;
96 private AreaDefinition areaDefinition;
97 private String name;
98 private String type;
99 private String dialog;
100 private String availableComponents;
101 private String label;
102 private String description;
103 private Boolean inherit;
104 private Boolean optional;
105 private Boolean editable;
106 private Integer maxComponents;
107 private Boolean createAreaNode;
108
109 private Map<String, Object> contextAttributes = new HashMap<String, Object>();
110
111 private String areaPath;
112
113 private boolean isAreaDefinitionEnabled;
114 private final RenderableVariationResolver variationResolver;
115
116 @Inject
117 public AreaElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine, RenderableVariationResolver variationResolver) {
118 super(server, renderingContext);
119 this.renderingEngine = renderingEngine;
120 this.variationResolver = variationResolver;
121 }
122
123
124
125
126 public AreaElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine) {
127 this(server, renderingContext, renderingEngine, Components.getComponent(RenderableVariationResolver.class));
128 }
129
130 @Override
131 public void begin(Appendable out) throws IOException, RenderException {
132
133 this.templateDefinition = resolveTemplateDefinition();
134 this.areaDefinition = resolveAreaDefinition();
135
136 this.isAreaDefinitionEnabled = areaDefinition != null && (areaDefinition.getEnabled() == null || areaDefinition.getEnabled());
137
138 if (!this.isAreaDefinitionEnabled) {
139 return;
140 }
141
142 this.name = resolveName();
143 this.dialog = resolveDialog();
144 this.type = resolveType();
145 this.label = resolveLabel();
146 this.availableComponents = resolveAvailableComponents();
147 this.inherit = isInheritanceEnabled();
148 this.optional = resolveOptional();
149 this.editable = resolveEditable();
150 this.createAreaNode = resolveCreateAreaNode();
151
152 this.description = templateDefinition.getDescription();
153
154
155 if (this.areaDefinition == null) {
156 buildAdHocAreaDefinition();
157 }
158
159 this.maxComponents = resolveMaximumOfComponents();
160
161
162 this.areaNode = getPassedContent();
163 if (this.areaNode != null) {
164 this.areaPath = getNodePath(areaNode);
165 }
166 else {
167
168
169 Node parentNode = currentContent();
170 if(createAreaNode){
171 this.areaNode = tryToCreateAreaNode(parentNode);
172 this.areaPath = getNodePath(parentNode) + "/" + name;
173 } else {
174 this.areaNode = parentNode;
175 this.areaPath = getNodePath(parentNode);
176 }
177 }
178
179 if (renderComments()) {
180 MarkupHelper helper = new MarkupHelper(out);
181
182 helper.openComment(CMS_AREA).attribute(AbstractDirective.CONTENT_ATTRIBUTE, this.areaPath);
183 helper.attribute("name", this.name);
184 helper.attribute("availableComponents", this.availableComponents);
185 helper.attribute("type", this.type);
186 helper.attribute("dialog", this.dialog);
187
188 final String i18nBasename = StringUtils.isNotEmpty(areaDefinition.getI18nBasename()) ? areaDefinition.getI18nBasename() : templateDefinition.getI18nBasename();
189 Messages messages = MessagesManager.getMessages(i18nBasename);
190 helper.attribute("label", messages.getWithDefault(this.label, this.label));
191
192 helper.attribute("inherit", String.valueOf(this.inherit));
193 if (this.editable != null) {
194 helper.attribute("editable", String.valueOf(this.editable));
195 }
196 helper.attribute("optional", String.valueOf(this.optional));
197 if (isOptionalAreaCreated()) {
198 helper.attribute("created", "true");
199 }
200 helper.attribute("createAreaNode", String.valueOf(this.createAreaNode));
201 helper.attribute("showAddButton", String.valueOf(shouldShowAddButton()));
202 helper.attribute("showNewComponentArea", String.valueOf(this.shouldShowAddNewComponent()));
203 if (StringUtils.isNotBlank(description)) {
204 helper.attribute("description", messages.getWithDefault(description, description));
205 }
206
207 helper.append(" -->\n");
208
209 }
210 }
211
212 private boolean hasPermission(Node node) {
213 if (node == null) {
214 node = currentContent();
215 }
216 try {
217 return node.getSession().hasPermission(node.getPath(), Session.ACTION_SET_PROPERTY);
218 } catch (RepositoryException e) {
219 log.error("Could not determine permission for node {}", node);
220 }
221 return false;
222 }
223
224 private Node createNewAreaNode(Node parentNode) throws RepositoryException {
225 final String parentId = parentNode.getIdentifier();
226 final String workspaceName = parentNode.getSession().getWorkspace().getName();
227 try {
228
229 MgnlContext.doInSystemContext(new MgnlContext.LockingOp(workspaceName, parentNode.getPath(), NodeTypes.Page.NAME) {
230
231 @Override
232 public void doExec() throws RepositoryException {
233 Node parentNodeInSystemSession = NodeUtil.getNodeByIdentifier(workspaceName, parentId);
234 Node newAreaNode = NodeUtil.createPath(parentNodeInSystemSession, AreaElement.this.name, NodeTypes.Area.NAME);
235 newAreaNode.getSession().save();
236 }
237 });
238 } catch (LockException e) {
239
240 log.warn("Failed to create area due to locking problem. " + e.getMessage(), e);
241 } catch (PathNotFoundException e) {
242
243 log.warn("Failed to create area due to concurrent deletion of page or the parent area. " + e.getMessage(), e);
244 }
245
246 parentNode.getSession().refresh(true);
247 return parentNode.getNode(this.name);
248 }
249
250 protected void buildAdHocAreaDefinition() {
251 ConfiguredAreaDefinition addHocAreaDefinition = new ConfiguredAreaDefinition();
252 addHocAreaDefinition.setName(this.name);
253 addHocAreaDefinition.setDialog(this.dialog);
254 addHocAreaDefinition.setType(this.type);
255 addHocAreaDefinition.setRenderType(this.templateDefinition.getRenderType());
256 areaDefinition = addHocAreaDefinition;
257 }
258
259 @Override
260 public void end(Appendable out) throws RenderException {
261
262 try {
263 if (canRenderAreaScript()) {
264 if (isInherit() && areaNode != null && areaDefinition.getInheritance() != null) {
265 try {
266 areaNode = new DefaultInheritanceContentDecorator(areaNode, areaDefinition.getInheritance()).wrapNode(areaNode);
267 } catch (RepositoryException e) {
268 throw new RuntimeRepositoryException(e);
269 }
270 }
271 List<Node> listOfComponents = null;
272 int numberOfComponents = 0;
273 if (areaNode != null) {
274 listOfComponents = NodeUtil.asList(NodeUtil.getNodes(areaNode, NodeTypes.Component.NAME));
275 numberOfComponents = listOfComponents.size();
276 }
277 if (renderingEngine.getRenderEmptyAreas() || numberOfComponents > 0 || !(AreaDefinition.TYPE_LIST.equals(areaDefinition.getType()) || AreaDefinition.TYPE_SINGLE.equals(areaDefinition.getType()))) {
278
279 Map<String, Object> contextObjects = new HashMap<String, Object>();
280
281 List<ContentMap> components = new ArrayList<ContentMap>();
282
283 if (areaNode != null) {
284 if (numberOfComponents > maxComponents) {
285 listOfComponents = listOfComponents.subList(0, maxComponents);
286 log.warn("The area {} have maximum number of components set to {}, but has got " + numberOfComponents +
287 " components. Exceeded components won't be added.", areaNode, maxComponents);
288 }
289
290 for (Node node : listOfComponents) {
291 components.add(new ContentMap(node));
292 }
293 }
294
295 if (AreaDefinition.TYPE_SINGLE.equals(type)) {
296 if (components.size() > 1) {
297 log.warn("Single area [{}]: expected one component node but found [{}].", areaNode, components.size());
298 }
299 if (components.size() >= 1) {
300 contextObjects.put(ATTRIBUTE_COMPONENT, components.get(0));
301 } else {
302 contextObjects.put(ATTRIBUTE_COMPONENT, null);
303 }
304 } else {
305 contextObjects.put(ATTRIBUTE_COMPONENTS, components);
306 }
307
308
309 if (areaDefinition instanceof ConfiguredAreaDefinition) {
310 if (areaDefinition.getTemplateScript() == null) {
311 ((ConfiguredAreaDefinition) areaDefinition).setRenderType("noscript");
312 } else if (areaDefinition.getRenderType() == null) {
313 ((ConfiguredAreaDefinition) areaDefinition).setRenderType(this.templateDefinition.getRenderType());
314 }
315
316 if (areaDefinition.getI18nBasename() == null) {
317 ((ConfiguredAreaDefinition) areaDefinition).setI18nBasename(this.templateDefinition.getI18nBasename());
318 }
319 }
320
321 WebContext webContext = MgnlContext.getWebContext();
322 webContext.push(webContext.getRequest(), webContext.getResponse());
323 setAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
324 try {
325 AppendableOnlyOutputProvider appendable = new AppendableOnlyOutputProvider(out);
326 renderingEngine.render(areaNode, areaDefinition, contextObjects, appendable);
327 } finally {
328 webContext.pop();
329 webContext.setPageContext(null);
330 restoreAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE);
331 }
332 }
333 }
334 if (renderComments()) {
335 MarkupHelper helper = new MarkupHelper(out);
336 helper.closeComment(CMS_AREA);
337 }
338 } catch (Exception e) {
339 throw new RenderException("Can't render area " + areaNode + " with name " + this.name, e);
340 }
341 }
342
343 protected Node tryToCreateAreaNode(Node parentNode) throws RenderException {
344 Node area = null;
345 try {
346 if (parentNode.hasNode(name)) {
347 area = parentNode.getNode(name);
348 } else {
349
350 if (!this.optional) {
351 area = createNewAreaNode(parentNode);
352 }
353 }
354 } catch (RepositoryException e) {
355
356 log.error("Can't autocreate area '{}'.", area, e);
357 }
358
359 if (area != null) {
360
361 final AutoGenerationConfiguration autoGeneration = areaDefinition.getAutoGeneration();
362 if (autoGeneration != null && autoGeneration.getGeneratorClass() != null) {
363 try {
364 final String areaId = area.getIdentifier();
365 final String workspaceName = area.getSession().getWorkspace().getName();
366 MgnlContext.doInSystemContext(new MgnlContext.RepositoryOp() {
367 @Override
368 public void doExec() throws RepositoryException {
369 Node areaNodeInSystemSession = NodeUtil.getNodeByIdentifier(workspaceName, areaId);
370 try {
371 ((Generator<AutoGenerationConfiguration>) Components.newInstance(autoGeneration.getGeneratorClass(), areaNodeInSystemSession)).generate(autoGeneration);
372 } catch (RenderException e) {
373 log.error("Can't render autogenerated area '{}'.", areaNodeInSystemSession);
374 }
375 return;
376 }
377 });
378 } catch (RepositoryException e) {
379 log.error("Can't autocreate area '{}'.", area, e);
380 }
381 }
382 }
383 return area;
384 }
385
386 protected AreaDefinition resolveAreaDefinition() {
387 if (areaDefinition != null) {
388 return areaDefinition;
389 }
390
391 if (!StringUtils.isEmpty(name)) {
392 if (templateDefinition != null && templateDefinition.getAreas().containsKey(name)) {
393 return templateDefinition.getAreas().get(name);
394 }
395 }
396
397
398 return null;
399 }
400
401 protected TemplateDefinition resolveTemplateDefinition() throws RenderException {
402
403 RenderableDefinition renderableDefinition = getRenderingContext().getRenderableDefinition();
404 RenderableDefinition variation = variationResolver.resolveVariation(renderableDefinition);
405 renderableDefinition = variation == null ? renderableDefinition : variation;
406
407 if (renderableDefinition == null || renderableDefinition instanceof TemplateDefinition) {
408 return (TemplateDefinition) renderableDefinition;
409 }
410 throw new RenderException("Current RenderableDefinition [" + renderableDefinition + "] is not of type TemplateDefinition. Areas cannot be supported");
411 }
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431 private boolean canRenderAreaScript() {
432 if (!this.isAreaDefinitionEnabled) {
433 return false;
434 }
435 if (this.areaNode != null) {
436 return true;
437 }
438 if (this.optional && this.getServer().isAdmin() && !MgnlContext.getAggregationState().isPreviewMode()) {
439 return true;
440 }
441 return false;
442 }
443
444 private String resolveDialog() {
445 return dialog != null ? dialog : areaDefinition != null ? areaDefinition.getDialog() : null;
446 }
447
448 private String resolveType() {
449 return type != null ? type : areaDefinition != null && areaDefinition.getType() != null ? areaDefinition.getType() : AreaDefinition.DEFAULT_TYPE;
450 }
451
452 private String resolveName() {
453 return name != null ? name : areaDefinition != null ? areaDefinition.getName() : null;
454 }
455
456 private String resolveLabel() {
457 return label != null ? label : areaDefinition != null && StringUtils.isNotBlank(areaDefinition.getTitle()) ? areaDefinition.getTitle() : StringUtils.capitalize(name);
458 }
459
460 private Boolean resolveOptional() {
461 return optional != null ? optional : areaDefinition != null && areaDefinition.getOptional() != null ? areaDefinition.getOptional() : Boolean.FALSE;
462 }
463
464 private Boolean resolveEditable() {
465 return editable != null ? editable : areaDefinition != null && areaDefinition.getEditable() != null ? areaDefinition.getEditable() : null;
466 }
467
468 private Integer resolveMaximumOfComponents() {
469 return maxComponents != null ? maxComponents : areaDefinition != null && areaDefinition.getMaxComponents() != null ? areaDefinition.getMaxComponents() : Integer.MAX_VALUE;
470 }
471
472 private Boolean resolveCreateAreaNode() {
473 return createAreaNode != null ? createAreaNode : areaDefinition != null && areaDefinition.getCreateAreaNode() != null ? areaDefinition.getCreateAreaNode() : Boolean.TRUE;
474 }
475
476 private boolean isInheritanceEnabled() {
477 return areaDefinition != null && areaDefinition.getInheritance() != null && areaDefinition.getInheritance().isEnabled() != null && areaDefinition.getInheritance().isEnabled();
478 }
479
480 private boolean isOptionalAreaCreated() {
481 return this.optional && this.areaNode != null;
482 }
483
484 private boolean hasComponents(Node parent) throws RenderException {
485 try {
486 return NodeUtil.getNodes(parent, NodeTypes.Component.NAME).iterator().hasNext();
487 } catch (RepositoryException e) {
488 throw new RenderException(e);
489 }
490 }
491
492 private int numberOfComponents(Node parent) throws RenderException {
493 try {
494 return NodeUtil.asList(NodeUtil.getNodes(parent, NodeTypes.Component.NAME)).size();
495 } catch (RepositoryException e) {
496 throw new RenderException(e);
497 }
498 }
499
500 protected String resolveAvailableComponents() {
501 if (StringUtils.isNotEmpty(availableComponents)) {
502 return StringUtils.remove(availableComponents, " ");
503 }
504 if (areaDefinition != null && areaDefinition.getAvailableComponents().size() > 0) {
505 Iterator<ComponentAvailability> iterator = areaDefinition.getAvailableComponents().values().iterator();
506 List<String> componentIds = new ArrayList<String>();
507 final Collection<String> userRoles = MgnlContext.getUser().getAllRoles();
508 while (iterator.hasNext()) {
509 ComponentAvailability availableComponent = iterator.next();
510 if (availableComponent.isEnabled()) {
511
512 final Collection<String> roles = availableComponent.getRoles();
513 if (!roles.isEmpty()) {
514 if (CollectionUtils.containsAny(userRoles, roles)) {
515 componentIds.add(availableComponent.getId());
516 }
517 } else {
518 componentIds.add(availableComponent.getId());
519 }
520 }
521 }
522 return StringUtils.join(componentIds, ',');
523 }
524 return "";
525 }
526
527 private boolean shouldShowAddButton() throws RenderException {
528
529 if (areaNode == null || type.equals(AreaDefinition.TYPE_NO_COMPONENT) || type.equals(AreaDefinition.TYPE_SINGLE) && hasComponents(areaNode) || numberOfComponents(areaNode) >= maxComponents) {
530 return false;
531 }
532 return true;
533 }
534
535 private boolean shouldShowAddNewComponent() throws RenderException {
536
537 if (areaNode == null || type.equals(AreaDefinition.TYPE_NO_COMPONENT) || type.equals(AreaDefinition.TYPE_SINGLE) && hasComponents(areaNode)) {
538 return false;
539 }
540 return true;
541 }
542
543 public String getName() {
544 return name;
545 }
546
547 public void setName(String name) {
548 this.name = name;
549 }
550
551 public AreaDefinition getArea() {
552 return areaDefinition;
553 }
554
555 public void setArea(AreaDefinition area) {
556 this.areaDefinition = area;
557 }
558
559 public String getAvailableComponents() {
560 return availableComponents;
561 }
562
563 public void setAvailableComponents(String availableComponents) {
564 this.availableComponents = availableComponents;
565 }
566
567 public String getType() {
568 return type;
569 }
570
571 public void setType(String type) {
572 this.type = type;
573 }
574
575 public String getDialog() {
576 return dialog;
577 }
578
579 public void setDialog(String dialog) {
580 this.dialog = dialog;
581 }
582
583 public String getLabel() {
584 return label;
585 }
586
587 public void setLabel(String label) {
588 this.label = label;
589 }
590
591 public String getDescription() {
592 return description;
593 }
594
595 public void setDescription(String description) {
596 this.description = description;
597 }
598
599 public boolean isInherit() {
600 return inherit;
601 }
602
603 public void setInherit(boolean inherit) {
604 this.inherit = inherit;
605 }
606
607 public Boolean getEditable() {
608 return editable;
609 }
610
611 public void setEditable(Boolean editable) {
612 this.editable = editable;
613 }
614
615 public Map<String, Object> getContextAttributes() {
616 return contextAttributes;
617 }
618
619 public void setContextAttributes(Map<String, Object> contextAttributes) {
620 this.contextAttributes = contextAttributes;
621 }
622
623 public Integer getMaxComponents() {
624 return maxComponents;
625 }
626
627 public void setMaxComponents(Integer maxComponents) {
628 this.maxComponents = maxComponents;
629 }
630
631 public Boolean getCreateAreaNode() {
632 return createAreaNode;
633 }
634
635 public void setCreateAreaNode(Boolean createAreaNode) {
636 this.createAreaNode = createAreaNode;
637 }
638
639 @Override
640 protected boolean renderComments() {
641 return this.isAreaDefinitionEnabled && isAdmin() && !MgnlContext.getAggregationState().isPreviewMode() && hasPermission(this.areaNode);
642 }
643 }