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