View Javadoc
1   /**
2    * This file Copyright (c) 2008-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.module.admininterface.trees;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.ItemType;
38  import info.magnolia.cms.core.MetaData;
39  import info.magnolia.cms.core.MgnlNodeType;
40  import info.magnolia.cms.core.Path;
41  import info.magnolia.cms.exchange.ExchangeException;
42  import info.magnolia.cms.gui.control.Select;
43  import info.magnolia.cms.gui.control.TreeColumn;
44  import info.magnolia.cms.i18n.Messages;
45  import info.magnolia.cms.i18n.MessagesManager;
46  import info.magnolia.cms.i18n.MessagesUtil;
47  import info.magnolia.context.Context;
48  import info.magnolia.context.MgnlContext;
49  import info.magnolia.jcr.predicate.NodeTypePredicate;
50  import info.magnolia.jcr.util.MetaDataUtil;
51  import info.magnolia.jcr.util.NodeUtil;
52  import info.magnolia.module.admininterface.AdminTreeMVCHandler;
53  import info.magnolia.objectfactory.Components;
54  import info.magnolia.registry.RegistrationException;
55  import info.magnolia.rendering.template.TemplateDefinition;
56  import info.magnolia.rendering.template.assignment.TemplateDefinitionAssignment;
57  import info.magnolia.rendering.template.registry.TemplateDefinitionRegistry;
58  
59  import java.util.Collection;
60  import java.util.Collections;
61  
62  import javax.jcr.Node;
63  import javax.jcr.RepositoryException;
64  import javax.jcr.Session;
65  import javax.servlet.http.HttpServletRequest;
66  import javax.servlet.http.HttpServletResponse;
67  
68  import org.slf4j.Logger;
69  import org.slf4j.LoggerFactory;
70  
71  /**
72   * @author philipp
73   * @version $Id$
74   */
75  public class WebsiteTreeHandler extends AdminTreeMVCHandler {
76      private static final Logger log = LoggerFactory.getLogger(WebsiteTreeHandler.class);
77  
78      private static final String COMMAND_SHOW_TEMPLATES = "getTemplatesHtml";
79      private static final String COMMAND_CHECK_CHILDREN_MODIFIED = "checkIfChildrenModified";
80  
81      private TemplateDefinitionRegistry templateRegistry;
82      private TemplateDefinitionAssignment templateAssignment;
83      private boolean getAvailableTemplates;
84      private boolean checkIfChildrenModified;
85  
86      public WebsiteTreeHandler(String name, HttpServletRequest request, HttpServletResponse response) {
87          super(name, request, response);
88          // TODO dlipp: use IoC.
89          templateAssignment = Components.getComponent(TemplateDefinitionAssignment.class);
90          templateRegistry = Components.getComponent(TemplateDefinitionRegistry.class);
91      }
92  
93      @Override
94      public String createNode() {
95          String view = super.createNode();
96          try {
97              // todo: default template
98              if (this.getCreateItemType().equals(ItemType.PAGE.getSystemName())) {
99                  // TODO dlipp: use JCR-API directly
100                 Content parentNode = this.getHierarchyManager().getContent(this.getPath());
101                 Content newNode = parentNode.getContent(this.getNewNodeName());
102                 TemplateDefinition newTemplate = getDefaultTemplate(newNode.getJCRNode());
103                 if (newTemplate != null) {
104                     newNode.getMetaData().setTemplate(newTemplate.getId());
105                     newNode.save();
106                 }
107             }
108         } catch (RepositoryException e) {
109             log.error("can't set template", e);
110         }
111         return view;
112     }
113 
114     protected TemplateDefinition getDefaultTemplate(Node node) {
115         return templateAssignment.getDefaultTemplate(node);
116     }
117 
118     @Override
119     public String show() {
120         // show start page if no templates present yet or if only available template is mgnlDeleted
121         Collection<TemplateDefinition> templateDefinitions = templateRegistry.getTemplateDefinitions();
122         // TODO I know this hardcoded check is ugly but could not find a better way
123         boolean isDeletedNodeTemplate = templateDefinitions.size() == 1 && "adminInterface:mgnlDeleted".equals(templateDefinitions.iterator().next().getId());
124         if (templateDefinitions.isEmpty() || isDeletedNodeTemplate) {
125             try {
126                 request.getRequestDispatcher("/.magnolia/pages/quickstart.html").forward(request, response);
127                 return "";
128             } catch (Exception e) {
129                 log.error("Couldn't forward to quickstart page: " + e.getMessage());
130             }
131         }
132         return super.show();
133     }
134 
135     @Override
136     public String getCommand() {
137         if (isGetAvailableTemplates()) {
138             return COMMAND_SHOW_TEMPLATES;
139         } else if (isCheckIfChildrenModified()) {
140             return COMMAND_CHECK_CHILDREN_MODIFIED;
141         }
142         return super.getCommand();
143     }
144 
145     public String getTemplatesHtml() {
146         String javascriptTree = getTree().getJavascriptTree();
147         Select templateSelect = new Select();
148         templateSelect.setName(javascriptTree + TreeColumn.EDIT_NAMEADDITION);
149         templateSelect.setSaveInfo(false);
150         templateSelect.setCssClass(TreeColumn.EDIT_CSSCLASS_SELECT);
151 
152         templateSelect.setEvent("onblur", javascriptTree + ".saveNodeData(this.value,this.options[this.selectedIndex].text)");
153         templateSelect.setEvent("onchange", javascriptTree + ".saveNodeData(this.value,this.options[this.selectedIndex].text)");
154 
155         Collection<TemplateDefinition> templateDefinitons = Collections.emptyList();
156         try {
157             templateDefinitons = templateAssignment.getAvailableTemplates(MgnlContext.getJCRSession(this.getRepository()).getNode(this.getPath()));
158         } catch (RepositoryException e) {
159             log.error(e.getMessage(), e);
160         }
161 
162         templateSelect.getOptions().clear();
163 
164         for (TemplateDefinition templateDefinition : templateDefinitons) {
165             String title = MessagesUtil.javaScriptString(getI18nTitle(templateDefinition));
166             templateSelect.setOptions(title, templateDefinition.getId());
167         }
168         this.displayValue = templateSelect.getHtml();
169         return VIEW_VALUE;
170     }
171 
172     public String checkIfChildrenModified() {
173         String path = this.getRequest().getParameter(Context.ATTRIBUTE_PATH);
174 
175         try {
176             Session session = MgnlContext.getJCRSession(getRepository());
177             Node node = session.getNode(path);
178 
179             for (Node child : NodeUtil.collectAllChildren(node, new NodeTypePredicate(node.getPrimaryNodeType().getName()))) {
180                 if (MetaData.ACTIVATION_STATUS_MODIFIED == MetaDataUtil.getMetaData(child).getActivationStatus()) {
181                     this.displayValue = child.getPath();
182                     return VIEW_VALUE; // returning of all nodes could impact performance
183                 }
184             }
185         } catch (RepositoryException e) {
186             log.error("Cannot check if children of '{}:{}' were modified", new Object[] { getRepository(), path }, e);
187         }
188         this.displayValue = "";
189         return VIEW_VALUE;
190     }
191 
192     private String getI18nTitle(TemplateDefinition template) {
193         Messages messages = MessagesManager.getMessages(template.getI18nBasename());
194         String title = template.getTitle();
195         return messages.getWithDefault(title, title);
196     }
197 
198     @Override
199     protected void copyOrMove(int action) throws ExchangeException, RepositoryException {
200         String pathClipboard = this.getRequest().getParameter("pathClipboard");
201         if (isCopyOrMoveAvailable(pathSelected, pathClipboard)) {
202             super.copyOrMove(action);
203         } else {
204             throw new RuntimeException("Template of the page is not available on this level");
205         }
206     }
207 
208     protected boolean isCopyOrMoveAvailable(String targetPath, String pagePath) throws RepositoryException {
209         boolean result = false;
210         try {
211             Session session = MgnlContext.getJCRSession(getRepository());
212             String tempNodeName = Path.getUniqueLabel(session, targetPath, "temporaryNode");
213             Node targetPage = session.getNode(targetPath).addNode(tempNodeName, MgnlNodeType.NT_PAGE);
214             Node movedPage = session.getNode(pagePath);
215 
216             TemplateDefinitionRegistry registry = Components.getComponent(TemplateDefinitionRegistry.class);
217             TemplateDefinition definition = registry.getTemplateDefinition(movedPage.getNode("MetaData").getProperty("mgnl:template").getString());
218 
219             result = templateAssignment.getAvailableTemplates(targetPage).contains(definition);
220 
221             session.refresh(false);
222         } catch (RegistrationException e) {
223             throw new RuntimeException("Template availability could not be resolved");
224         }
225         return result;
226     }
227 
228     public boolean isGetAvailableTemplates() {
229         return getAvailableTemplates;
230     }
231 
232     public void setGetAvailableTemplates(boolean getAvailableTemplates) {
233         this.getAvailableTemplates = getAvailableTemplates;
234     }
235 
236     public boolean isCheckIfChildrenModified() {
237         return checkIfChildrenModified;
238     }
239 
240     public void setCheckIfChildrenModified(boolean checkIfChildrenModified) {
241         this.checkIfChildrenModified = checkIfChildrenModified;
242     }
243 }