View Javadoc
1   /**
2    * This file Copyright (c) 2012-2015 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.jsp.taglib;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.Content.ContentFilter;
38  import info.magnolia.cms.core.ItemType;
39  import info.magnolia.cms.core.NodeData;
40  import info.magnolia.cms.i18n.I18nContentSupportFactory;
41  import info.magnolia.cms.util.ContentUtil;
42  import info.magnolia.context.MgnlContext;
43  
44  import java.io.IOException;
45  import java.util.ArrayList;
46  import java.util.Collection;
47  import java.util.Iterator;
48  import java.util.List;
49  
50  import javax.jcr.Node;
51  import javax.jcr.RepositoryException;
52  import javax.servlet.http.HttpServletRequest;
53  import javax.servlet.jsp.JspException;
54  import javax.servlet.jsp.JspWriter;
55  import javax.servlet.jsp.tagext.TagSupport;
56  
57  import org.apache.commons.lang.StringEscapeUtils;
58  import org.apache.commons.lang.StringUtils;
59  import org.apache.commons.lang.exception.NestableRuntimeException;
60  import org.slf4j.Logger;
61  import org.slf4j.LoggerFactory;
62  import org.tldgen.annotations.BodyContent;
63  import org.tldgen.annotations.Tag;
64  
65  /**
66   * Draws a simple, css based, navigation menu. The menu layout can then be customized using css, and the default menu
67   * should be enough for most uses. Two following page properties will also be used in the menu:
68   * <ul>
69   * <li><code>navTitle</code>: a title to use for the navigation menu, if different from the real page title</li>
70   * <li><code>accessKey</code>: an optional access key which will be added to the link</li>
71   * <li><code>wrappingElement</code>: an optional html element (div, span, p, etc) to go within the &lt;a&gt; tag wrapping the anchor text
72   * </ul>
73   * 
74   * @jsp.tag name="simpleNavigation" body-content="empty"
75   * @jsp.tag-example
76   * <pre>
77   * &lt;cmsu:simpleNavigation startLevel="3" style="mystyle"/&gt;
78   * 
79   * Will output the following:
80   * 
81   * &lt;ul class="level3 mystyle"&gt;
82   *     &lt;li&gt;&lt;a href="..."&gt;page 1 name &lt;/a&gt;&lt;/li&gt;
83   *     &lt;li&gt;&lt;a href="..."&gt;page 2 name &lt;/a&gt;&lt;/li&gt;
84   *     &lt;li class="trail"&gt;&lt;a href="..."&gt;page 3 name &lt;/a&gt;
85   *         &lt;ul class="level3"&gt;
86   *             &lt;li&gt;&lt;a href="..."&gt;subpage 1 name &lt;/a&gt;&lt;/li&gt;
87   *             &lt;li&gt;&lt;a href="..."&gt;subpage 2 name &lt;/a&gt;&lt;/li&gt;
88   *             &lt;li&gt;&lt;strong&gt;&lt;a href="..."&gt;selected page name &lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
89   *         &lt;/ul&gt;
90   *     &lt;/li&gt;
91   *     &lt;li&gt;&lt;a href="..."&gt;page 4 name &lt;/a&gt;&lt;/li&gt;
92   * &lt;/ul&gt;
93   * </pre>
94   */
95  @Tag(name = "simpleNavigation", bodyContent = BodyContent.EMPTY)
96  public class SimpleNavigationTag extends TagSupport {
97  
98      /**
99       * Css class added to active page.
100      */
101     private static final String CSS_LI_ACTIVE = "active";
102 
103     /**
104      * Css class added to ancestor of the active page.
105      */
106     private static final String CSS_LI_TRAIL = "trail";
107 
108     /**
109      * Css class added to leaf pages.
110      */
111     private static final String CSS_LI_LEAF = "leaf";
112 
113     /**
114      * Css class added to open trees.
115      */
116     private static final String CSS_LI_CLOSED = "closed";
117 
118     /**
119      * Css class added to closed trees.
120      */
121     private static final String CSS_LI_OPEN = "open";
122 
123     /**
124      * Css class added to first li in ul.
125      */
126     private static final String CSS_LI_FIRST = "first";
127 
128     /**
129      * Css class added to last li in ul.
130      */
131     private static final String CSS_LI_LAST = "last";
132 
133     /**
134      * Page property: navigation title.
135      */
136     private static final String NODEDATA_NAVIGATIONTITLE = "navTitle";
137 
138     /**
139      * Page property: access key.
140      */
141     public static final String NODEDATA_ACCESSKEY = "accessKey";
142 
143     /**
144      * Default name for "open menu" nodeData.
145      */
146     public static final String DEFAULT_OPENMENU_NODEDATA = "openMenu";
147 
148     /**
149      * Default name for "hide in nav" nodeData.
150      */
151     public static final String DEFAULT_HIDEINNAV_NODEDATA = "hideInNav";
152 
153     /**
154      * Default name for "wrapperElement" nodeData.
155      */
156     public static final String DEFAULT_WRAPPERELEMENT_NODEDATA = "";
157 
158     /**
159      * Expand all expand all the nodes.
160      */
161     public static final String EXPAND_ALL = "all";
162 
163     /**
164      * Expand all expand only page that should be displayed in navigation.
165      */
166     public static final String EXPAND_SHOW = "show";
167 
168     /**
169      * Do not use expand functions.
170      */
171     public static final String EXPAND_NONE = "none";
172 
173     private static Logger log = LoggerFactory.getLogger(SimpleNavigationTag.class);
174 
175     /**
176      * Start level.
177      */
178     private int startLevel;
179 
180     /**
181      * End level.
182      */
183     private int endLevel;
184 
185     /**
186      * Name for the "hide in nav" nodeData.
187      */
188     private String hideInNav;
189 
190     /**
191      * Name for the "open menu" nodeData.
192      */
193     private String openMenu;
194 
195     /**
196      * Style to apply to the menu.
197      */
198     private String style;
199 
200     /**
201      * html element to wrap the anchortext. (i.e. &lt;a&gt;&lt;wrapper&gt;...&lt;/wrapper&gt;&lt;/a&gt;)
202      */
203     public String wrapperElement;
204 
205     /**
206      * Expand all the nodes. (sitemap mode)
207      */
208     private String expandAll = EXPAND_NONE;
209 
210     private boolean relativeLevels = false;
211 
212     /**
213      * Name for a page property which will be written to the css class attribute.
214      */
215     private String classProperty;
216 
217     /**
218      * Name for the "nofollow" hodeData (for link that must be ignored by search engines).
219      */
220     private String nofollow;
221 
222     /**
223      * Content Filter to use to evaluate if a page should be drawn.
224      */
225     private ContentFilter filter;
226 
227     private String contentFilter = "";
228 
229     /**
230      * Flag to set if the first and last li in each ul should be marked with a special css class.
231      */
232     private boolean markFirstAndLastElement = false;
233 
234     /**
235      * The start level for navigation, defaults to 0.
236      * 
237      * @jsp.attribute required="false" rtexprvalue="true" type="int"
238      */
239     public void setStartLevel(int startLevel) {
240         this.startLevel = startLevel;
241     }
242 
243     /**
244      * The end level for navigation, defaults to 0.
245      * 
246      * @jsp.attribute required="false" rtexprvalue="true" type="int"
247      */
248     public void setEndLevel(int endLevel) {
249         this.endLevel = endLevel;
250     }
251 
252     /**
253      * The css class to be applied to the first ul. Default is empty.
254      * 
255      * @jsp.attribute required="false" rtexprvalue="true"
256      */
257     public void setStyle(String style) {
258         this.style = style;
259     }
260 
261     /**
262      * Name for the "hide in nav" nodeData. If a page contains a boolean property with this name and
263      * it is set to true, the page is not shown in navigation. Defaults to "hideInNav".
264      * 
265      * @jsp.attribute required="false" rtexprvalue="true"
266      */
267     public void setHideInNav(String hideInNav) {
268         this.hideInNav = hideInNav;
269     }
270 
271     /**
272      * Name for the "open menu" nodeData. If a page contains a boolean property with this name and
273      * it is set to true, subpages are always shown also if the page is not selected.
274      * Defaults to "openMenu".
275      * 
276      * @jsp.attribute required="false" rtexprvalue="true"
277      */
278     public void setOpenMenu(String openMenu) {
279         this.openMenu = openMenu;
280     }
281 
282     /**
283      * Name for the "nofollow" nodeData. If a page contains a boolean property with this name
284      * and it is set to true, rel="nofollow" will be added to the generated link
285      * (for links the should be ignored by search engines).
286      * 
287      * @jsp.attribute required="false" rtexprvalue="true"
288      */
289     public void setNofollow(String nofollow) {
290         this.nofollow = nofollow;
291     }
292 
293     /**
294      * A variable in the pageContext that contains a content filter, determining if a given page should be drawn or not.
295      * 
296      * @jsp.attribute required="false" rtexprvalue="true"
297      */
298     public void setContentFilter(String contentFilter) {
299         this.contentFilter = contentFilter;
300     }
301 
302     /**
303      * Sitemap mode. Can be assigned the "show" value. Only showable pages will be displayed. Any other value will
304      * result in displaying all pages.
305      * 
306      * @jsp.attribute required="false" rtexprvalue="true"
307      */
308     public void setExpandAll(String expandAll) {
309         if (expandAll.equalsIgnoreCase(EXPAND_SHOW)) {
310             this.expandAll = expandAll;
311         }
312         else {
313             this.expandAll = EXPAND_ALL;
314         }
315     }
316 
317     /**
318      * If set to true, the startLevel and endLevel values are treated relatively to the current active page.
319      * The default value is false.
320      * 
321      * @jsp.attribute required="false" rtexprvalue="true" type="boolean"
322      */
323     public void setRelativeLevels(boolean relativeLevels) {
324         this.relativeLevels = relativeLevels;
325     }
326 
327     /**
328      * Name for a page property that will hold a css class name which will be added to the html class attribute.
329      * 
330      * @jsp.attribute required="false" rtexprvalue="true"
331      */
332     public void setClassProperty(String classProperty) {
333         this.classProperty = classProperty;
334     }
335 
336     /**
337      * When specified, all links will have the anchortext wrapped in the supplied element. (such as "span")
338      * 
339      * @param wrapperElement name of an html element that will be included in the anchor, wrapping the anchortext
340      * @jsp.attribute required="false" rtexprvalue="true"
341      */
342     public void setWrapperElement(String wrapperElement) {
343         this.wrapperElement = wrapperElement;
344     }
345 
346     /**
347      * If set to true, a "first" or "last" css class will be added to the list of css classes of the
348      * first and the last li in each ul.
349      * 
350      * @jsp.attribute required="false" rtexprvalue="true" type="boolean"
351      */
352     public void setMarkFirstAndLastElement(boolean flag) {
353         markFirstAndLastElement = flag;
354     }
355 
356     @Override
357     public int doEndTag() throws JspException {
358         Content activePage = getCurrentActivePage();
359         try {
360             while (!ItemType.PAGE.getSystemName().equals(activePage.getNodeTypeName()) && activePage.getLevel() != 0) {
361                 activePage = activePage.getParent();
362             }
363         } catch (RepositoryException e) {
364             log.error("Failed to obtain parent page for " + getCurrentActivePage().getHandle(), e);
365             activePage = getCurrentActivePage();
366         }
367         JspWriter out = this.pageContext.getOut();
368 
369         if (StringUtils.isNotEmpty(this.contentFilter)) {
370             try {
371                 filter = (ContentFilter) this.pageContext.getAttribute(this.contentFilter);
372             } catch (ClassCastException e) {
373                 log.error("contentFilter assigned was not a content filter", e);
374             }
375         } else {
376             filter = null;
377         }
378 
379         if (startLevel > endLevel) {
380             endLevel = 0;
381         }
382 
383         try {
384             final int activePageLevel = activePage.getLevel();
385             // if we are to treat the start and end level as relative
386             // to the active page, we adjust them here...
387             if (relativeLevels) {
388                 this.startLevel += activePageLevel;
389                 this.endLevel += activePageLevel;
390             }
391             if (this.startLevel <= activePageLevel) {
392                 Content startContent = activePage.getAncestor(this.startLevel);
393                 drawChildren(startContent, activePage, out);
394             }
395 
396         } catch (RepositoryException e) {
397             log.error("RepositoryException caught while drawing navigation: " + e.getMessage(), e);
398             return EVAL_PAGE;
399         } catch (IOException e) {
400             // should never happen
401             throw new NestableRuntimeException(e);
402         }
403 
404         return EVAL_PAGE;
405     }
406 
407     @Override
408     public void release() {
409         this.startLevel = 0;
410         this.endLevel = 0;
411         this.hideInNav = null;
412         this.openMenu = null;
413         this.style = null;
414         this.classProperty = null;
415         this.expandAll = EXPAND_NONE;
416         this.relativeLevels = false;
417         this.wrapperElement = "";
418         this.contentFilter = "";
419         this.filter = null;
420         this.nofollow = null;
421         this.markFirstAndLastElement = false;
422         super.release();
423     }
424 
425     /**
426      * Draws page children as an unordered list.
427      * 
428      * @param page current page
429      * @param activePage active page
430      * @param out jsp writer
431      * @throws IOException jspwriter exception
432      * @throws RepositoryException any exception thrown during repository reading
433      */
434     private void drawChildren(Content page, Content activePage, JspWriter out) throws IOException, RepositoryException {
435 
436         Collection<Content> children = new ArrayList<Content>(page.getChildren(ItemType.CONTENT));
437 
438         if (children.size() == 0) {
439             return;
440         }
441 
442         out.print("<ul class=\"level");
443         out.print(page.getLevel());
444         if (style != null && page.getLevel() == startLevel) {
445             out.print(" ");
446             out.print(style);
447         }
448         out.print("\">");
449 
450         Iterator<Content> iter = children.iterator();
451         // loop through all children and discard those we don't want to display
452         while (iter.hasNext()) {
453             final Content child = iter.next();
454 
455             if (expandAll.equalsIgnoreCase(EXPAND_NONE) || expandAll.equalsIgnoreCase(EXPAND_SHOW)) {
456                 if (child
457                         .getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)).getBoolean()) {
458                     iter.remove();
459                     continue;
460                 }
461                 // use a filter
462                 if (filter != null) {
463                     if (!filter.accept(child)) {
464                         iter.remove();
465                         continue;
466                     }
467                 }
468             } else {
469                 if (child.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)).getBoolean()) {
470                     iter.remove();
471                     continue;
472                 }
473             }
474         }
475 
476         boolean isFirst = true;
477         Iterator<Content> visibleIt = children.iterator();
478         while (visibleIt.hasNext()) {
479             Content child = visibleIt.next();
480             List<String> cssClasses = new ArrayList<String>(4);
481 
482             NodeData nodeData = I18nContentSupportFactory.getI18nSupport().getNodeData(child, NODEDATA_NAVIGATIONTITLE);
483             String title = null;
484             if(nodeData != null){
485                 title = nodeData.getString(StringUtils.EMPTY);
486             }
487 
488             // if nav title is not set, the main title is taken
489             if (StringUtils.isEmpty(title)) {
490                 title = child.getTitle();
491             }
492 
493             // if main title is not set, the name of the page is taken
494             if (StringUtils.isEmpty(title)) {
495                 title = child.getName();
496             }
497 
498             boolean showChildren = false;
499             boolean self = false;
500 
501             if (!expandAll.equalsIgnoreCase(EXPAND_NONE)) {
502                 showChildren = true;
503             }
504 
505             if (activePage.getHandle().equals(child.getHandle())) {
506                 // self
507                 showChildren = true;
508                 self = true;
509                 cssClasses.add(CSS_LI_ACTIVE);
510             }
511             else if (!showChildren) {
512                 showChildren = child.getLevel() <= activePage.getAncestors().size() && StringUtils.equals(activePage.getAncestor(child.getLevel()).getHandle(), child.getHandle());
513             }
514 
515             if (!showChildren) {
516                 showChildren = child
517                         .getNodeData(StringUtils.defaultString(this.openMenu, DEFAULT_OPENMENU_NODEDATA))
518                         .getBoolean();
519             }
520 
521             if (endLevel > 0) {
522                 showChildren &= child.getLevel() < endLevel;
523             }
524 
525             cssClasses.add(hasVisibleChildren(child) ? showChildren ? CSS_LI_OPEN : CSS_LI_CLOSED : CSS_LI_LEAF);
526 
527             if (child.getLevel() < activePage.getLevel()
528                     && activePage.getAncestor(child.getLevel()).getHandle().equals(child.getHandle())) {
529                 cssClasses.add(CSS_LI_TRAIL);
530             }
531 
532             if (StringUtils.isNotEmpty(classProperty) && child.hasNodeData(classProperty)) {
533                 cssClasses.add(child.getNodeData(classProperty).getString(StringUtils.EMPTY));
534             }
535 
536             if (markFirstAndLastElement && isFirst) {
537                 cssClasses.add(CSS_LI_FIRST);
538                 isFirst = false;
539             }
540 
541             if (markFirstAndLastElement && !visibleIt.hasNext()) {
542                 cssClasses.add(CSS_LI_LAST);
543             }
544 
545             StringBuffer css = new StringBuffer(cssClasses.size() * 10);
546             Iterator<String> iterator = cssClasses.iterator();
547             while (iterator.hasNext()) {
548                 css.append(iterator.next());
549                 if (iterator.hasNext()) {
550                     css.append(" ");
551                 }
552             }
553 
554             out.print("<li class=\"");
555             out.print(css.toString());
556             out.print("\">");
557 
558             if (self) {
559                 out.println("<strong>");
560             }
561 
562             String accesskey = null;
563             if(child.getNodeData(NODEDATA_ACCESSKEY) != null){
564                 accesskey = child.getNodeData(NODEDATA_ACCESSKEY).getString(StringUtils.EMPTY);
565             }
566 
567             out.print("<a href=\"");
568             out.print(((HttpServletRequest) this.pageContext.getRequest()).getContextPath());
569             out.print(I18nContentSupportFactory.getI18nSupport().toI18NURI(child.getHandle()));
570             out.print(".html\"");
571 
572             if (StringUtils.isNotEmpty(accesskey)) {
573                 out.print(" accesskey=\"");
574                 out.print(accesskey);
575                 out.print("\"");
576             }
577 
578             if (nofollow != null && child.getNodeData(this.nofollow).getBoolean())
579             {
580                 out.print(" rel=\"nofollow\"");
581             }
582 
583             out.print(">");
584 
585             if (StringUtils.isNotEmpty(this.wrapperElement)) {
586                 out.print("<" + this.wrapperElement + ">");
587             }
588 
589             out.print(StringEscapeUtils.escapeHtml(title));
590 
591             if (StringUtils.isNotEmpty(this.wrapperElement)) {
592                 out.print("</" + this.wrapperElement + ">");
593             }
594 
595             out.print(" </a>");
596 
597             if (self) {
598                 out.println("</strong>");
599             }
600 
601             if (showChildren) {
602                 drawChildren(child, activePage, out);
603             }
604             out.print("</li>");
605         }
606 
607         out.print("</ul>");
608     }
609 
610     /**
611      * Checks if the page has a visible children. Pages with the <code>hide in nav</code> attribute set to <code>true</code> are ignored.
612      * 
613      * @param page root page
614      * @return <code>true</code> if the given page has at least one visible child.
615      */
616     private boolean hasVisibleChildren(Content page) {
617         Collection<Content> children = page.getChildren();
618         if (children.size() > 0 && expandAll.equalsIgnoreCase(EXPAND_ALL)) {
619             return true;
620         }
621         for (Content ch : children) {
622             if (!ch.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)).getBoolean()) {
623                 return true;
624             }
625         }
626         return false;
627     }
628 
629     protected Node getCurrentActivePageNode() {
630         Node currentActpage = MgnlContext.getAggregationState().getCurrentContentNode();
631         if (currentActpage == null) {
632             currentActpage = MgnlContext.getAggregationState().getMainContentNode();
633         }
634         return currentActpage;
635     }
636 
637     /**
638      * @deprecated since 4.5 - use #getCurrentActivePageNode instead.
639      */
640     protected Content getCurrentActivePage() {
641         return ContentUtil.asContent(getCurrentActivePageNode());
642     }
643 }