View Javadoc

1   /**
2    * This file Copyright (c) 2011-2014 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.functions;
35  
36  import info.magnolia.cms.beans.config.ServerConfiguration;
37  import info.magnolia.cms.core.AggregationState;
38  import info.magnolia.cms.core.NodeData;
39  import info.magnolia.cms.i18n.I18nContentSupportFactory;
40  import info.magnolia.cms.util.ContentUtil;
41  import info.magnolia.cms.util.QueryUtil;
42  import info.magnolia.cms.util.SiblingsHelper;
43  import info.magnolia.jcr.inheritance.InheritanceNodeWrapper;
44  import info.magnolia.jcr.util.ContentMap;
45  import info.magnolia.jcr.util.MetaDataUtil;
46  import info.magnolia.jcr.util.NodeTypes;
47  import info.magnolia.jcr.util.NodeUtil;
48  import info.magnolia.jcr.util.PropertyUtil;
49  import info.magnolia.jcr.util.SessionUtil;
50  import info.magnolia.jcr.wrapper.HTMLEscapingNodeWrapper;
51  import info.magnolia.link.LinkUtil;
52  import info.magnolia.objectfactory.Components;
53  import info.magnolia.rendering.template.configured.ConfiguredInheritance;
54  import info.magnolia.repository.RepositoryConstants;
55  import info.magnolia.templating.inheritance.DefaultInheritanceContentDecorator;
56  
57  import java.net.URI;
58  import java.net.URISyntaxException;
59  import java.util.ArrayList;
60  import java.util.Calendar;
61  import java.util.Collection;
62  import java.util.List;
63  
64  import javax.inject.Inject;
65  import javax.inject.Provider;
66  import javax.jcr.Node;
67  import javax.jcr.PathNotFoundException;
68  import javax.jcr.Property;
69  import javax.jcr.PropertyType;
70  import javax.jcr.RepositoryException;
71  
72  import org.apache.commons.lang3.StringUtils;
73  import org.apache.jackrabbit.util.ISO8601;
74  import org.slf4j.Logger;
75  import org.slf4j.LoggerFactory;
76  
77  /**
78   * An object exposing several methods useful for templates. It is exposed in templates as <code>cmsfn</code>.
79   */
80  public class TemplatingFunctions {
81  
82      private static final Logger log = LoggerFactory.getLogger(TemplatingFunctions.class);
83  
84      private final Provider<AggregationState> aggregationStateProvider;
85  
86      //TODO: To review with Philipp. Should not use Provider, but has deep impact on CategorizationSupportImpl PageSyndicator CategorySyndicator....
87      @Inject
88      public TemplatingFunctions(Provider<AggregationState> aggregationStateProvider) {
89          this.aggregationStateProvider = aggregationStateProvider;
90      }
91  
92  
93      public Node asJCRNode(ContentMap contentMap) {
94          return contentMap == null ? null : contentMap.getJCRNode();
95      }
96  
97      public ContentMap asContentMap(Node content) {
98          return content == null ? null : new ContentMap(content);
99      }
100 
101     public List<Node> children(Node content) throws RepositoryException {
102         return content == null ? null : asNodeList(NodeUtil.getNodes(content, NodeUtil.EXCLUDE_META_DATA_FILTER));
103     }
104 
105     public List<Node> children(Node content, String nodeTypeName) throws RepositoryException {
106         return content == null ? null : asNodeList(NodeUtil.getNodes(content, nodeTypeName));
107     }
108 
109     public List<ContentMap> children(ContentMap content) throws RepositoryException {
110         return content == null ? null : asContentMapList(NodeUtil.getNodes(asJCRNode(content), NodeUtil.EXCLUDE_META_DATA_FILTER));
111     }
112 
113     public List<ContentMap> children(ContentMap content, String nodeTypeName) throws RepositoryException {
114         return content == null ? null : asContentMapList(NodeUtil.getNodes(asJCRNode(content), nodeTypeName));
115     }
116 
117     public ContentMap root(ContentMap contentMap) throws RepositoryException {
118         return contentMap == null ? null : asContentMap(this.root(contentMap.getJCRNode()));
119     }
120 
121     public ContentMap root(ContentMap contentMap, String nodeTypeName) throws RepositoryException {
122         return contentMap == null ? null : asContentMap(this.root(contentMap.getJCRNode(), nodeTypeName));
123     }
124 
125     public Node root(Node content) throws RepositoryException {
126         return this.root(content, null);
127     }
128 
129     public Node root(Node content, String nodeTypeName) throws RepositoryException {
130         if (content == null) {
131             return null;
132         }
133         if (nodeTypeName == null) {
134             return (Node) content.getAncestor(0);
135         }
136         if (isRoot(content) && content.isNodeType(nodeTypeName)) {
137             return content;
138         }
139 
140         Node parentNode = this.parent(content, nodeTypeName);
141         while (parent(parentNode, nodeTypeName) != null) {
142             parentNode = this.parent(parentNode, nodeTypeName);
143         }
144         return parentNode;
145     }
146 
147     public ContentMap parent(ContentMap contentMap) throws RepositoryException {
148         return contentMap == null ? null : asContentMap(this.parent(contentMap.getJCRNode()));
149     }
150 
151     public ContentMap parent(ContentMap contentMap, String nodeTypeName) throws RepositoryException {
152         return contentMap == null ? null : asContentMap(this.parent(contentMap.getJCRNode(), nodeTypeName));
153     }
154 
155     public Node parent(Node content) throws RepositoryException {
156         return this.parent(content, null);
157     }
158 
159     public Node parent(Node content, String nodeTypeName) throws RepositoryException {
160         if (content == null) {
161             return null;
162         }
163         if (isRoot(content)) {
164             return null;
165         }
166         if (nodeTypeName == null) {
167             return content.getParent();
168         }
169         Node parent = content.getParent();
170         while (!parent.isNodeType(nodeTypeName)) {
171             if (isRoot(parent)) {
172                 return null;
173             }
174             parent = parent.getParent();
175         }
176         return parent;
177     }
178 
179     /**
180      * Returns the page's {@link ContentMap} of the passed {@link ContentMap}. If the passed {@link ContentMap} represents a page, the passed {@link ContentMap} will be returned.
181      * If the passed {@link ContentMap} has no parent page at all, null is returned.
182      *
183      * @param content the {@link ContentMap} to get the page's {@link ContentMap} from.
184      * @return returns the page {@link ContentMap} of the passed content {@link ContentMap}.
185      */
186     public ContentMap page(ContentMap content) throws RepositoryException {
187         return content == null ? null : asContentMap(page(content.getJCRNode()));
188     }
189 
190     /**
191      * Returns the page {@link Node} of the passed node. If the passed {@link Node} is a page, the passed {@link Node} will be returned.
192      * If the passed Node has no parent page at all, null is returned.
193      *
194      * @param content the {@link Node} to get the page from.
195      * @return returns the page {@link Node} of the passed content {@link Node}.
196      */
197     public Node page(Node content) throws RepositoryException {
198         if (content == null) {
199             return null;
200         }
201         if (content.isNodeType(NodeTypes.Page.NAME)) {
202             return content;
203         }
204         return parent(content, NodeTypes.Page.NAME);
205     }
206 
207     public List<ContentMap> ancestors(ContentMap contentMap) throws RepositoryException {
208         return ancestors(contentMap, null);
209     }
210 
211     public List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName) throws RepositoryException {
212         List<Node> ancestorsAsNodes = this.ancestors(contentMap.getJCRNode(), nodeTypeName);
213         return asContentMapList(ancestorsAsNodes);
214     }
215 
216     public List<Node> ancestors(Node content) throws RepositoryException {
217         return content == null ? null : this.ancestors(content, null);
218     }
219 
220     public List<Node> ancestors(Node content, String nodeTypeName) throws RepositoryException {
221         if (content == null) {
222             return null;
223         }
224         List<Node> ancestors = new ArrayList<Node>();
225         int depth = content.getDepth();
226         for (int i = 1; i < depth; ++i) {
227             Node possibleAncestor = (Node) content.getAncestor(i);
228             if (nodeTypeName == null) {
229                 ancestors.add(possibleAncestor);
230             } else {
231                 if (possibleAncestor.isNodeType(nodeTypeName)) {
232                     ancestors.add(possibleAncestor);
233                 }
234             }
235         }
236         return ancestors;
237     }
238 
239     public Node inherit(Node content) throws RepositoryException {
240         return inherit(content, null);
241     }
242 
243     public Node inherit(Node content, String relPath) throws RepositoryException {
244         if (content == null) {
245             return null;
246         }
247         Node inheritedNode = wrapForInheritance(content);
248 
249         if (StringUtils.isBlank(relPath)) {
250             return inheritedNode;
251         }
252 
253         try {
254             Node subNode = inheritedNode.getNode(relPath);
255             return NodeUtil.unwrap(subNode);
256         } catch (PathNotFoundException e) {
257             // TODO fgrilli: rethrow exception?
258         }
259         return null;
260     }
261 
262     public ContentMap inherit(ContentMap content) throws RepositoryException {
263         return inherit(content, null);
264     }
265 
266     public ContentMap inherit(ContentMap content, String relPath) throws RepositoryException {
267         if (content == null) {
268             return null;
269         }
270         Node node = inherit(content.getJCRNode(), relPath);
271         return node == null ? null : new ContentMap(node);
272     }
273 
274 
275     public Property inheritProperty(Node content, String relPath) throws RepositoryException {
276         if (content == null) {
277             return null;
278         }
279         if (StringUtils.isBlank(relPath)) {
280             throw new IllegalArgumentException("relative path cannot be null or empty");
281         }
282         try {
283             Node inheritedNode = wrapForInheritance(content);
284             return inheritedNode.getProperty(relPath);
285 
286         } catch (PathNotFoundException e) {
287             // TODO fgrilli: rethrow exception?
288         } catch (RepositoryException e) {
289             // TODO fgrilli:rethrow exception?
290         }
291 
292         return null;
293     }
294 
295     public Property inheritProperty(ContentMap content, String relPath) throws RepositoryException {
296         if (content == null) {
297             return null;
298         }
299         return inheritProperty(content.getJCRNode(), relPath);
300     }
301 
302     public List<Node> inheritList(Node content, String relPath) throws RepositoryException {
303         if (content == null) {
304             return null;
305         }
306         if (StringUtils.isBlank(relPath)) {
307             throw new IllegalArgumentException("relative path cannot be null or empty");
308         }
309         Node inheritedNode = wrapForInheritance(content);
310         Node subNode = inheritedNode.getNode(relPath);
311         return children(subNode);
312     }
313 
314     public List<ContentMap> inheritList(ContentMap content, String relPath) throws RepositoryException {
315         if (content == null) {
316             return null;
317         }
318         if (StringUtils.isBlank(relPath)) {
319             throw new IllegalArgumentException("relative path cannot be null or empty");
320         }
321         Node node = asJCRNode(content);
322         Node inheritedNode = wrapForInheritance(node);
323         Node subNode = inheritedNode.getNode(relPath);
324         return children(new ContentMap(subNode));
325     }
326 
327     public boolean isInherited(Node content) {
328         if (content instanceof InheritanceNodeWrapper) {
329             return ((InheritanceNodeWrapper) content).isInherited();
330         }
331         return false;
332     }
333 
334     public boolean isInherited(ContentMap content) {
335         return isInherited(asJCRNode(content));
336     }
337 
338     public boolean isFromCurrentPage(Node content) {
339         return !isInherited(content);
340     }
341 
342     public boolean isFromCurrentPage(ContentMap content) {
343         return isFromCurrentPage(asJCRNode(content));
344     }
345 
346     /**
347      * Create link for the Node identified by nodeIdentifier in the specified workspace.
348      */
349     public String link(String workspace, String nodeIdentifier) {
350         try {
351             return LinkUtil.createLink(workspace, nodeIdentifier);
352         } catch (RepositoryException e) {
353             return null;
354         }
355     }
356 
357     /**
358      * There should be no real reason to use this method except to produce link to binary content stored in jcr:data property in which case one should call {@link #link(Node)} while passing parent node as a parameter. In case you find other valid reason to use this method, please raise it in a forum discussion or create issue. Otherwise this method will be removed in the future.
359      *
360      * @deprecated since 4.5.4. There is no valid use case for this method.
361      */
362     @Deprecated
363     public String link(Property property) {
364         try {
365             Node parentNode = null;
366             String propertyName = null;
367             if (property.getType() == PropertyType.BINARY) {
368                 parentNode = property.getParent().getParent();
369                 propertyName = property.getParent().getName();
370             } else {
371                 parentNode = property.getParent();
372                 propertyName = property.getName();
373             }
374             NodeData equivNodeData = ContentUtil.asContent(parentNode).getNodeData(propertyName);
375             return LinkUtil.createLink(equivNodeData);
376         } catch (Exception e) {
377             return null;
378         }
379     }
380 
381     public String link(Node content) {
382         return content == null ? null : LinkUtil.createLink(content);
383     }
384 
385     public String link(ContentMap contentMap) throws RepositoryException {
386         return contentMap == null ? null : this.link(asJCRNode(contentMap));
387     }
388 
389     /**
390      * Returns the querystring and fragment of a url, or an empty string if there are none.
391      */
392     public String getQueryStringAndFragment(String url){
393         String result = "";
394         try {
395             URI uri = new URI(url);
396             String query = uri.getQuery();
397             String fragment = uri.getFragment();
398 
399             if (StringUtils.isNotEmpty(query)){
400                 result += "?" + query;
401             }
402             if (StringUtils.isNotEmpty(fragment)){
403                 result += "#" + fragment;
404             }
405         } catch (URISyntaxException e) {
406             log.warn("URL cannot be parsed. {0}, {1}", url, e.getMessage());
407             return StringUtils.EMPTY;
408         }
409         return result;
410     }
411 
412     /**
413      * Get the language used currently.
414      * @return The language as a String.
415      */
416     public String language(){
417         return I18nContentSupportFactory.getI18nSupport().getLocale().toString();
418     }
419     /**
420      * Returns an external link prepended with <code>http://</code> in case the protocol is missing or an empty String
421      * if the link does not exist.
422      *
423      * @param content The node where the link property is stored on.
424      * @param linkPropertyName The property where the link value is stored in.
425      * @return The link prepended with <code>http://</code>
426      */
427     public String externalLink(Node content, String linkPropertyName) {
428         String externalLink = PropertyUtil.getString(content, linkPropertyName);
429         if (StringUtils.isBlank(externalLink)) {
430             return StringUtils.EMPTY;
431         }
432         if (!hasProtocol(externalLink)) {
433             externalLink = "http://" + externalLink;
434         }
435         return externalLink;
436     }
437 
438     /**
439      * Returns an external link prepended with <code>http://</code> in case the protocol is missing or an empty String
440      * if the link does not exist.
441      *
442      * @param content The node's map representation where the link property is stored on.
443      * @param linkPropertyName The property where the link value is stored in.
444      * @return The link prepended with <code>http://</code>
445      */
446     public String externalLink(ContentMap content, String linkPropertyName) {
447         return externalLink(asJCRNode(content), linkPropertyName);
448     }
449 
450     /**
451      * Return a link title based on the @param linkTitlePropertyName. When property @param linkTitlePropertyName is
452      * empty or null, the link itself is provided as the linkTitle (prepended with <code>http://</code>).
453      *
454      * @param content The node where the link property is stored on.
455      * @param linkPropertyName The property where the link value is stored in.
456      * @param linkTitlePropertyName The property where the link title value is stored
457      * @return the resolved link title value
458      */
459     public String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName) {
460         String linkTitle = PropertyUtil.getString(content, linkTitlePropertyName);
461         if (StringUtils.isNotEmpty(linkTitle)) {
462             return linkTitle;
463         }
464         return externalLink(content, linkPropertyName);
465     }
466 
467     /**
468      * Return a link title based on the @param linkTitlePropertyName. When property @param linkTitlePropertyName is
469      * empty or null, the link itself is provided as the linkTitle (prepended with <code>http://</code>).
470      *
471      * @param content The node where the link property is stored on.
472      * @param linkPropertyName The property where the link value is stored in.
473      * @param linkTitlePropertyName The property where the link title value is stored
474      * @return the resolved link title value
475      */
476     public String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName) {
477         return externalLinkTitle(asJCRNode(content), linkPropertyName, linkTitlePropertyName);
478     }
479 
480     public boolean isEditMode() {
481         // TODO : see CmsFunctions.isEditMode, which checks a couple of other properties.
482         return isAuthorInstance() && !isPreviewMode();
483     }
484 
485     public boolean isPreviewMode() {
486         return this.aggregationStateProvider.get().isPreviewMode();
487     }
488 
489     public boolean isAuthorInstance() {
490         return Components.getComponent(ServerConfiguration.class).isAdmin();
491     }
492 
493     public boolean isPublicInstance() {
494         return !isAuthorInstance();
495     }
496 
497     /**
498      * Util method to create html attributes <code>name="value"</code>. If the value is empty an empty string will be returned.
499      * This is mainly helpful to avoid empty attributes.
500      */
501     public String createHtmlAttribute(String name, String value) {
502         value = StringUtils.trim(value);
503         if (StringUtils.isNotEmpty(value)) {
504             return new StringBuffer().append(name).append("=\"").append(value).append("\"").toString();
505         }
506         return StringUtils.EMPTY;
507     }
508 
509     /**
510      * Returns an instance of SiblingsHelper for the given node.
511      */
512     public SiblingsHelper siblings(Node node) throws RepositoryException {
513         return SiblingsHelper.of(ContentUtil.asContent(node));
514     }
515 
516     public SiblingsHelper siblings(ContentMap node) throws RepositoryException {
517         return siblings(asJCRNode(node));
518     }
519 
520     /**
521      * Return the Node for the given path from the website repository.
522      *
523      * @deprecated since 5.3.3 use {@link #contentByPath(String)} or {@link #nodeByPath(String)} instead
524      */
525     public Node content(String path){
526         return content(RepositoryConstants.WEBSITE, path);
527     }
528 
529     /**
530      * Return the Node for the given path from the given repository.
531      * @deprecated since 5.3.3 use {@link #contentByPath(String, String)} or {@link #nodeByPath(String, String)} instead
532      */
533     public Node content(String repository, String path){
534         return SessionUtil.getNode(repository, path);
535     }
536 
537     /**
538      * Return the Node by the given identifier from the website repository.
539      *
540      * @deprecated since 5.3.3 use {@link #contentById(String)} or {@link #nodeById(String) instead
541      */
542     public Node contentByIdentifier(String id){
543         return contentByIdentifier(RepositoryConstants.WEBSITE, id);
544     }
545 
546     /**
547      * Return the Node by the given identifier from the given repository.
548      *
549      * @deprecated since 5.3.3 use {@link #contentById(String, String)} or {@link #contentByPath(String, String )} instead
550      */
551     public Node contentByIdentifier(String repository, String id) {
552         return SessionUtil.getNodeByIdentifier(repository, id);
553     }
554 
555     /**
556      * Return the ContentMap for the given path from the website repository.
557      */
558     public ContentMap contentByPath(String path) {
559         return contentByPath(path, RepositoryConstants.WEBSITE);
560     }
561 
562     /**
563      * Return the ContentMap for the given path from the given repository.
564      */
565     public ContentMap contentByPath(String path, String workspace) {
566         return asContentMap(nodeByPath(path, workspace));
567     }
568 
569     /**
570      * Return the ContentMap by the given identifier from the website repository.
571      */
572     public ContentMap contentById(String id) {
573         return contentById(id, RepositoryConstants.WEBSITE);
574     }
575 
576     /**
577      * Return the ContentMap by the given identifier from the given repository.
578      */
579     public ContentMap contentById(String id, String workspace) {
580         return asContentMap(SessionUtil.getNodeByIdentifier(workspace, id));
581     }
582 
583     /**
584      * Return the Node for the given path from the website repository.
585      */
586     public Node nodeByPath(String path) {
587         return nodeByPath(path, RepositoryConstants.WEBSITE);
588     }
589 
590     /**
591      * Return the Node for the given path from the given repository.
592      */
593     public Node nodeByPath(String path, String workspace) {
594         try {
595             String pathToNode = new URI(path).getPath();
596             return SessionUtil.getNode(workspace, pathToNode);
597         } catch (URISyntaxException e) {
598             log.warn("Path cannot be parsed. {0}, {1}", path, e.getMessage());
599             return null;
600         }
601     }
602 
603     /**
604      * Return the Node by the given identifier from the website repository.
605      */
606     public Node nodeById(String id) {
607         return nodeById(id, RepositoryConstants.WEBSITE);
608     }
609 
610     /**
611      * Return the Node by the given identifier from the given repository.
612      */
613     public Node nodeById(String id, String workspace) {
614         return SessionUtil.getNodeByIdentifier(workspace, id);
615     }
616 
617     public List<ContentMap> asContentMapList(Collection<Node> nodeList) {
618         if (nodeList != null) {
619             List<ContentMap> contentMapList = new ArrayList<ContentMap>();
620             for (Node node : nodeList) {
621                 contentMapList.add(asContentMap(node));
622             }
623             return contentMapList;
624         }
625         return null;
626     }
627 
628     public List<Node> asNodeList(Collection<ContentMap> contentMapList) {
629         if (contentMapList != null) {
630             List<Node> nodeList = new ArrayList<Node>();
631             for (ContentMap node : contentMapList) {
632                 nodeList.add(node.getJCRNode());
633             }
634             return nodeList;
635         }
636         return null;
637     }
638 
639     // TODO fgrilli: should we unwrap children?
640     protected List<Node> asNodeList(Iterable<Node> nodes) {
641         List<Node> childList = new ArrayList<Node>();
642         for (Node child : nodes) {
643             childList.add(child);
644         }
645         return childList;
646     }
647 
648     // TODO fgrilli: should we unwrap children?
649     protected List<ContentMap> asContentMapList(Iterable<Node> nodes) {
650         List<ContentMap> childList = new ArrayList<ContentMap>();
651         for (Node child : nodes) {
652             childList.add(new ContentMap(child));
653         }
654         return childList;
655     }
656 
657     /**
658      * Checks if passed string has a <code>http://</code> protocol.
659      *
660      * @param link The link to check
661      * @return If @param link contains a <code>http://</code> protocol
662      */
663     private boolean hasProtocol(String link) {
664         return link != null && link.contains("://");
665     }
666 
667     /**
668      * Checks if the passed {@link Node} is the jcr root '/' of the workspace.
669      * @param content {@link Node} to check if its root.
670      * @return if @param content is the jcr workspace root.
671      */
672     private boolean isRoot(Node content) throws RepositoryException {
673         return content.getDepth() == 0;
674     }
675 
676     /**
677      * Removes escaping of HTML on properties.
678      */
679     public ContentMap decode(ContentMap content){
680         return asContentMap(decode(content.getJCRNode()));
681     }
682 
683     /**
684      * Removes escaping of HTML on properties.
685      */
686     public Node decode(Node content) {
687         return NodeUtil.deepUnwrap(content, HTMLEscapingNodeWrapper.class);
688     }
689 
690     /**
691      * Adds escaping of HTML on properties as well as changing line breaks into &lt;br/&gt; tags.
692      */
693     public ContentMap encode(ContentMap content) {
694         return content != null ? new ContentMap(new HTMLEscapingNodeWrapper(content.getJCRNode(), true)) : null;
695     }
696 
697     /**
698      * Adds escaping of HTML on properties as well as changing line breaks into &lt;br/&gt; tags.
699      */
700     public Node encode(Node content) {
701         return content != null ? new HTMLEscapingNodeWrapper(content, true) : null;
702     }
703 
704     private Node wrapForInheritance(Node destination) throws RepositoryException {
705         ConfiguredInheritance inheritanceConfiguration = new ConfiguredInheritance();
706         inheritanceConfiguration.setEnabled(true);
707         return new DefaultInheritanceContentDecorator(destination, inheritanceConfiguration).wrapNode(destination);
708     }
709 
710     /**
711      * Returns the string representation of a property from the metaData of the node or <code>null</code> if the node has no Magnolia metaData or if no matching property is found.
712      */
713     public String metaData(Node content, String property){
714 
715         Object returnValue;
716         try {
717             if (property.equals(NodeTypes.Created.CREATED)) {
718                 returnValue = NodeTypes.Created.getCreated(content);
719             } else if (property.equals(NodeTypes.Created.CREATED_BY)) {
720                 returnValue = NodeTypes.Created.getCreatedBy(content);
721             } else if (property.equals(NodeTypes.LastModified.LAST_MODIFIED)) {
722                 returnValue = NodeTypes.LastModified.getLastModified(content);
723             } else if (property.equals(NodeTypes.LastModified.LAST_MODIFIED_BY)) {
724                 returnValue = NodeTypes.LastModified.getLastModifiedBy(content);
725             } else if (property.equals(NodeTypes.Renderable.TEMPLATE)) {
726                 returnValue = NodeTypes.Renderable.getTemplate(content);
727             } else if (property.equals(NodeTypes.Activatable.LAST_ACTIVATED)) {
728                 returnValue = NodeTypes.Activatable.getLastActivated(content);
729             } else if (property.equals(NodeTypes.Activatable.LAST_ACTIVATED_BY)) {
730                 returnValue = NodeTypes.Activatable.getLastActivatedBy(content);
731             } else if (property.equals(NodeTypes.Activatable.ACTIVATION_STATUS)) {
732                 returnValue = NodeTypes.Activatable.getActivationStatus(content);
733             } else if (property.equals(NodeTypes.Deleted.DELETED)) {
734                 returnValue = NodeTypes.Deleted.getDeleted(content);
735             } else if (property.equals(NodeTypes.Deleted.DELETED_BY)) {
736                 returnValue = NodeTypes.Deleted.getDeletedBy(content);
737             } else if (property.equals(NodeTypes.Deleted.COMMENT)) {
738                 // Since NodeTypes.Deleted.COMMENT and NodeTypes.Versionable.COMMENT have identical names this will work for both
739                 returnValue = NodeTypes.Deleted.getComment(content);
740             } else {
741 
742                 // Try to get the value using one of the deprecated names in MetaData.
743                 // This throws an IllegalArgumentException if its not one of those constants
744                 returnValue = MetaDataUtil.getMetaData(content).getStringProperty(property);
745 
746                 // If no exception was thrown then warn that a legacy constant was used
747                 log.warn("Deprecated constant [{}] used to query for meta data property on node [{}]", property, NodeUtil.getPathIfPossible(content));
748             }
749         } catch (RepositoryException e) {
750             return "";
751         }
752 
753         return returnValue instanceof Calendar ? ISO8601.format((Calendar) returnValue) : returnValue.toString();
754     }
755 
756     /**
757      * @see {@link TemplatingFunctions#metaData(Node, String)}.
758      */
759     public String metaData(ContentMap content, String property){
760         return metaData(content.getJCRNode(), property);
761     }
762 
763     /**
764      * Executes query and returns result as Collection of Nodes.
765      *
766      * @param statement has to be in formal form for chosen language
767      */
768     public Collection<Node> search(String workspace, String statement, String language, String returnItemType){
769         try {
770             return NodeUtil.getCollectionFromNodeIterator(QueryUtil.search(workspace, statement, language, returnItemType));
771         } catch (Exception e) {
772             log.error(e.getMessage(), e);
773         }
774         return null;
775     }
776 
777     /**
778      * Executes simple SQL2 query and returns result as Collection of Nodes.
779      *
780      * @param statement should be set of labels target has to contain inserted as one string each separated by comma
781      * @param startPath can be inserted, for results without limitation set it to slash
782      */
783     public Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath){
784         if(StringUtils.isEmpty(statement)){
785             log.error("Cannot search with empty statement.");
786             return null;
787         }
788         String query = QueryUtil.buildQuery(statement, startPath);
789         try {
790             return NodeUtil.getCollectionFromNodeIterator(QueryUtil.search(workspace, query, "JCR-SQL2", returnItemType));
791         } catch (Exception e) {
792             log.error(e.getMessage(), e);
793         }
794         return null;
795     }
796 }