Remove request from parser context
[Sone.git] / src / main / java / net / pterodactylus / sone / web / SoneTemplatePage.java
1 /*
2  * Sone - SoneTemplatePage.java - Copyright © 2010–2016 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web;
19
20 import java.io.UnsupportedEncodingException;
21 import java.net.URLEncoder;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28
29 import net.pterodactylus.sone.data.Sone;
30 import net.pterodactylus.sone.main.SonePlugin;
31 import net.pterodactylus.sone.web.page.FreenetRequest;
32 import net.pterodactylus.sone.web.page.FreenetTemplatePage;
33 import net.pterodactylus.util.notify.Notification;
34 import net.pterodactylus.util.template.Template;
35 import net.pterodactylus.util.template.TemplateContext;
36
37 import freenet.clients.http.SessionManager.Session;
38 import freenet.clients.http.ToadletContext;
39 import freenet.support.api.HTTPRequest;
40
41 import com.google.common.collect.ImmutableList;
42 import com.google.common.collect.ImmutableMap;
43
44 /**
45  * Base page for the Sone web interface.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class SoneTemplatePage extends FreenetTemplatePage {
50
51         /** The Sone core. */
52         protected final WebInterface webInterface;
53
54         /** The page title l10n key. */
55         private final String pageTitleKey;
56
57         /** Whether to require a login. */
58         private final boolean requireLogin;
59
60         /**
61          * Creates a new template page for Sone that does not require the user to be
62          * logged in.
63          *
64          * @param path
65          *            The path of the page
66          * @param template
67          *            The template to render
68          * @param pageTitleKey
69          *            The l10n key of the page title
70          * @param webInterface
71          *            The Sone web interface
72          */
73         public SoneTemplatePage(String path, Template template, String pageTitleKey, WebInterface webInterface) {
74                 this(path, template, pageTitleKey, webInterface, false);
75         }
76
77         /**
78          * Creates a new template page for Sone.
79          *
80          * @param path
81          *            The path of the page
82          * @param template
83          *            The template to render
84          * @param webInterface
85          *            The Sone web interface
86          * @param requireLogin
87          *            Whether this page requires a login
88          */
89         public SoneTemplatePage(String path, Template template, WebInterface webInterface, boolean requireLogin) {
90                 this(path, template, null, webInterface, requireLogin);
91         }
92
93         /**
94          * Creates a new template page for Sone.
95          *
96          * @param path
97          *            The path of the page
98          * @param template
99          *            The template to render
100          * @param pageTitleKey
101          *            The l10n key of the page title
102          * @param webInterface
103          *            The Sone web interface
104          * @param requireLogin
105          *            Whether this page requires a login
106          */
107         public SoneTemplatePage(String path, Template template, String pageTitleKey, WebInterface webInterface, boolean requireLogin) {
108                 super(path, webInterface.getTemplateContextFactory(), template, "noPermission.html");
109                 this.pageTitleKey = pageTitleKey;
110                 this.webInterface = webInterface;
111                 this.requireLogin = requireLogin;
112         }
113
114         //
115         // PROTECTED METHODS
116         //
117
118         /**
119          * Returns the current session, creating a new session if there is no
120          * current session.
121          *
122          * @param toadletContenxt
123          *            The toadlet context
124          * @return The current session, or {@code null} if there is no current
125          *         session
126          */
127         protected Session getCurrentSession(ToadletContext toadletContenxt) {
128                 return webInterface.getCurrentSession(toadletContenxt);
129         }
130
131         /**
132          * Returns the current session, creating a new session if there is no
133          * current session and {@code create} is {@code true}.
134          *
135          * @param toadletContenxt
136          *            The toadlet context
137          * @param create
138          *            {@code true} to create a new session if there is no current
139          *            session, {@code false} otherwise
140          * @return The current session, or {@code null} if there is no current
141          *         session
142          */
143         protected Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
144                 return webInterface.getCurrentSession(toadletContenxt, create);
145         }
146
147         /**
148          * Returns the currently logged in Sone.
149          *
150          * @param toadletContext
151          *            The toadlet context
152          * @return The currently logged in Sone, or {@code null} if no Sone is
153          *         currently logged in
154          */
155         protected Sone getCurrentSone(ToadletContext toadletContext) {
156                 return webInterface.getCurrentSone(toadletContext);
157         }
158
159         /**
160          * Returns the currently logged in Sone.
161          *
162          * @param toadletContext
163          *            The toadlet context
164          * @param create
165          *            {@code true} to create a new session if no session exists,
166          *            {@code false} to not create a new session
167          * @return The currently logged in Sone, or {@code null} if no Sone is
168          *         currently logged in
169          */
170         protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
171                 return webInterface.getCurrentSone(toadletContext, create);
172         }
173
174         /**
175          * Sets the currently logged in Sone.
176          *
177          * @param toadletContext
178          *            The toadlet context
179          * @param sone
180          *            The Sone to set as currently logged in
181          */
182         protected void setCurrentSone(ToadletContext toadletContext, Sone sone) {
183                 webInterface.setCurrentSone(toadletContext, sone);
184         }
185
186         //
187         // TEMPLATEPAGE METHODS
188         //
189
190         /**
191          * {@inheritDoc}
192          */
193         @Override
194         protected String getPageTitle(FreenetRequest request) {
195                 if (pageTitleKey != null) {
196                         return webInterface.getL10n().getString(pageTitleKey);
197                 }
198                 return "";
199         }
200
201         /**
202          * {@inheritDoc}
203          */
204         @Override
205         protected List<Map<String, String>> getAdditionalLinkNodes(FreenetRequest request) {
206                 return ImmutableList.<Map<String, String>> builder().add(ImmutableMap.<String, String> builder().put("rel", "search").put("type", "application/opensearchdescription+xml").put("title", "Sone").put("href", "http://" + request.getHttpRequest().getHeader("host") + "/Sone/OpenSearch.xml").build()).build();
207         }
208
209         /**
210          * {@inheritDoc}
211          */
212         @Override
213         protected Collection<String> getStyleSheets() {
214                 return Arrays.asList("css/sone.css");
215         }
216
217         /**
218          * {@inheritDoc}
219          */
220         @Override
221         protected String getShortcutIcon() {
222                 return "images/icon.png";
223         }
224
225         /**
226          * Returns whether this page requires the user to log in.
227          *
228          * @return {@code true} if the user is required to be logged in to use this
229          *         page, {@code false} otherwise
230          */
231         protected boolean requiresLogin() {
232                 return requireLogin;
233         }
234
235         /**
236          * {@inheritDoc}
237          */
238         @Override
239         protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
240                 super.processTemplate(request, templateContext);
241                 Sone currentSone = getCurrentSone(request.getToadletContext(), false);
242                 templateContext.set("core", webInterface.getCore());
243                 templateContext.set("currentSone", currentSone);
244                 templateContext.set("localSones", webInterface.getCore().getLocalSones());
245                 templateContext.set("request", request);
246                 templateContext.set("currentVersion", SonePlugin.getPluginVersion());
247                 templateContext.set("hasLatestVersion", webInterface.getCore().getUpdateChecker().hasLatestVersion());
248                 templateContext.set("latestEdition", webInterface.getCore().getUpdateChecker().getLatestEdition());
249                 templateContext.set("latestVersion", webInterface.getCore().getUpdateChecker().getLatestVersion());
250                 templateContext.set("latestVersionTime", webInterface.getCore().getUpdateChecker().getLatestVersionDate());
251                 List<Notification> notifications = new ArrayList<Notification>(webInterface.getNotifications(currentSone));
252                 Collections.sort(notifications, Notification.CREATED_TIME_SORTER);
253                 templateContext.set("notifications", notifications);
254                 templateContext.set("notificationHash", notifications.hashCode());
255         }
256
257         /**
258          * {@inheritDoc}
259          */
260         @Override
261         protected String getRedirectTarget(FreenetRequest request) {
262                 if (requiresLogin() && (getCurrentSone(request.getToadletContext(), false) == null)) {
263                         HTTPRequest httpRequest = request.getHttpRequest();
264                         String originalUrl = httpRequest.getPath();
265                         if (httpRequest.hasParameters()) {
266                                 StringBuilder requestParameters = new StringBuilder();
267                                 for (String parameterName : httpRequest.getParameterNames()) {
268                                         if (requestParameters.length() > 0) {
269                                                 requestParameters.append("%26");
270                                         }
271                                         String[] parameterValues = httpRequest.getMultipleParam(parameterName);
272                                         for (String parameterValue : parameterValues) {
273                                                 try {
274                                                         requestParameters.append(URLEncoder.encode(parameterName, "UTF-8")).append("%3d").append(URLEncoder.encode(parameterValue, "UTF-8"));
275                                                 } catch (UnsupportedEncodingException uee1) {
276                                                         /* A JVM without UTF-8? I don’t think so. */
277                                                 }
278                                         }
279                                 }
280                                 originalUrl += "?" + requestParameters.toString();
281                         }
282                         return "login.html?target=" + originalUrl;
283                 }
284                 return null;
285         }
286
287         /**
288          * {@inheritDoc}
289          */
290         @Override
291         protected boolean isFullAccessOnly() {
292                 return webInterface.getCore().getPreferences().isRequireFullAccess();
293         }
294
295         /**
296          * {@inheritDoc}
297          */
298         @Override
299         public boolean isEnabled(ToadletContext toadletContext) {
300                 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !toadletContext.isAllowedFullAccess()) {
301                         return false;
302                 }
303                 if (requiresLogin()) {
304                         return getCurrentSone(toadletContext, false) != null;
305                 }
306                 return true;
307         }
308
309 }