You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BasePage.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.wicket.pages;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.text.MessageFormat;
  20. import java.util.ArrayList;
  21. import java.util.Calendar;
  22. import java.util.Collections;
  23. import java.util.Date;
  24. import java.util.HashSet;
  25. import java.util.LinkedHashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.ResourceBundle;
  29. import java.util.Set;
  30. import java.util.TimeZone;
  31. import java.util.regex.Pattern;
  32. import javax.servlet.http.HttpServletRequest;
  33. import org.apache.commons.io.IOUtils;
  34. import org.apache.wicket.Application;
  35. import org.apache.wicket.Page;
  36. import org.apache.wicket.PageParameters;
  37. import org.apache.wicket.RedirectToUrlException;
  38. import org.apache.wicket.markup.html.CSSPackageResource;
  39. import org.apache.wicket.markup.html.basic.Label;
  40. import org.apache.wicket.markup.html.link.ExternalLink;
  41. import org.apache.wicket.markup.html.panel.FeedbackPanel;
  42. import org.apache.wicket.protocol.http.RequestUtils;
  43. import org.apache.wicket.protocol.http.WebResponse;
  44. import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
  45. import org.apache.wicket.util.time.Duration;
  46. import org.apache.wicket.util.time.Time;
  47. import org.slf4j.Logger;
  48. import org.slf4j.LoggerFactory;
  49. import com.gitblit.Constants;
  50. import com.gitblit.Constants.AccessPermission;
  51. import com.gitblit.Constants.AccessRestrictionType;
  52. import com.gitblit.Constants.AuthorizationControl;
  53. import com.gitblit.Constants.FederationStrategy;
  54. import com.gitblit.Keys;
  55. import com.gitblit.models.ProjectModel;
  56. import com.gitblit.models.TeamModel;
  57. import com.gitblit.models.UserModel;
  58. import com.gitblit.utils.StringUtils;
  59. import com.gitblit.utils.TimeUtils;
  60. import com.gitblit.wicket.CacheControl;
  61. import com.gitblit.wicket.GitBlitWebApp;
  62. import com.gitblit.wicket.GitBlitWebSession;
  63. import com.gitblit.wicket.WicketUtils;
  64. public abstract class BasePage extends SessionPage {
  65. private transient Logger logger;
  66. private transient TimeUtils timeUtils;
  67. public BasePage() {
  68. super();
  69. customizeHeader();
  70. }
  71. public BasePage(PageParameters params) {
  72. super(params);
  73. customizeHeader();
  74. }
  75. protected Logger logger() {
  76. if (logger == null) {
  77. logger = LoggerFactory.getLogger(getClass());
  78. }
  79. return logger;
  80. }
  81. private void customizeHeader() {
  82. if (app().settings().getBoolean(Keys.web.useResponsiveLayout, true)) {
  83. add(CSSPackageResource.getHeaderContribution("bootstrap/css/bootstrap-responsive.css"));
  84. }
  85. if (app().settings().getBoolean(Keys.web.hideHeader, false)) {
  86. add(CSSPackageResource.getHeaderContribution("hideheader.css"));
  87. }
  88. }
  89. protected String getContextUrl() {
  90. return getRequest().getRelativePathPrefixToContextRoot();
  91. }
  92. protected String getCanonicalUrl() {
  93. return getCanonicalUrl(getClass(), getPageParameters());
  94. }
  95. protected String getCanonicalUrl(Class<? extends BasePage> clazz, PageParameters params) {
  96. String relativeUrl = urlFor(clazz, params).toString();
  97. String canonicalUrl = RequestUtils.toAbsolutePath(relativeUrl);
  98. return canonicalUrl;
  99. }
  100. protected String getLanguageCode() {
  101. return GitBlitWebSession.get().getLocale().getLanguage();
  102. }
  103. protected String getCountryCode() {
  104. return GitBlitWebSession.get().getLocale().getCountry().toLowerCase();
  105. }
  106. protected TimeUtils getTimeUtils() {
  107. if (timeUtils == null) {
  108. ResourceBundle bundle;
  109. try {
  110. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp", GitBlitWebSession.get().getLocale());
  111. } catch (Throwable t) {
  112. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp");
  113. }
  114. timeUtils = new TimeUtils(bundle, getTimeZone());
  115. }
  116. return timeUtils;
  117. }
  118. @Override
  119. protected void onBeforeRender() {
  120. if (app().isDebugMode()) {
  121. // strip Wicket tags in debug mode for jQuery DOM traversal
  122. Application.get().getMarkupSettings().setStripWicketTags(true);
  123. }
  124. super.onBeforeRender();
  125. }
  126. @Override
  127. protected void onAfterRender() {
  128. if (app().isDebugMode()) {
  129. // restore Wicket debug tags
  130. Application.get().getMarkupSettings().setStripWicketTags(false);
  131. }
  132. super.onAfterRender();
  133. }
  134. @Override
  135. protected void setHeaders(WebResponse response) {
  136. // set canonical link as http header for SEO (issue-304)
  137. // https://support.google.com/webmasters/answer/139394?hl=en
  138. response.setHeader("Link", MessageFormat.format("<{0}>; rel=\"canonical\"", getCanonicalUrl()));
  139. int expires = app().settings().getInteger(Keys.web.pageCacheExpires, 0);
  140. if (expires > 0) {
  141. // pages are personalized for the authenticated user so they must be
  142. // marked private to prohibit proxy servers from caching them
  143. response.setHeader("Cache-Control", "private, must-revalidate");
  144. setLastModified();
  145. } else {
  146. // use default Wicket caching behavior
  147. super.setHeaders(response);
  148. }
  149. // XRF vulnerability. issue-500 / ticket-166
  150. response.setHeader("X-Frame-Options", "SAMEORIGIN");
  151. }
  152. /**
  153. * Sets the last-modified header date, if appropriate, for this page. The
  154. * date used is determined by the CacheControl annotation.
  155. *
  156. */
  157. protected void setLastModified() {
  158. if (getClass().isAnnotationPresent(CacheControl.class)) {
  159. CacheControl cacheControl = getClass().getAnnotation(CacheControl.class);
  160. switch (cacheControl.value()) {
  161. case ACTIVITY:
  162. setLastModified(app().getLastActivityDate());
  163. break;
  164. case BOOT:
  165. setLastModified(app().getBootDate());
  166. break;
  167. case NONE:
  168. break;
  169. default:
  170. logger().warn(getClass().getSimpleName() + ": unhandled LastModified type " + cacheControl.value());
  171. break;
  172. }
  173. }
  174. }
  175. /**
  176. * Sets the last-modified header field and the expires field.
  177. *
  178. * @param when
  179. */
  180. protected final void setLastModified(Date when) {
  181. if (when == null) {
  182. return;
  183. }
  184. if (when.before(app().getBootDate())) {
  185. // last-modified can not be before the Gitblit boot date
  186. // this helps ensure that pages are properly refreshed after a
  187. // server config change
  188. when = app().getBootDate();
  189. }
  190. int expires = app().settings().getInteger(Keys.web.pageCacheExpires, 0);
  191. WebResponse response = (WebResponse) getResponse();
  192. response.setLastModifiedTime(Time.valueOf(when));
  193. response.setDateHeader("Expires", System.currentTimeMillis() + Duration.minutes(expires).getMilliseconds());
  194. }
  195. protected String getPageTitle(String repositoryName) {
  196. String siteName = app().settings().getString(Keys.web.siteName, Constants.NAME);
  197. if (StringUtils.isEmpty(siteName)) {
  198. siteName = Constants.NAME;
  199. }
  200. if (repositoryName != null && repositoryName.trim().length() > 0) {
  201. return repositoryName + " - " + siteName;
  202. } else {
  203. return siteName;
  204. }
  205. }
  206. protected void setupPage(String repositoryName, String pageName) {
  207. add(new Label("title", getPageTitle(repositoryName)));
  208. String rootLinkUrl = app().settings().getString(Keys.web.rootLink, urlFor(GitBlitWebApp.get().getHomePage(), null).toString());
  209. ExternalLink rootLink = new ExternalLink("rootLink", rootLinkUrl);
  210. WicketUtils.setHtmlTooltip(rootLink, app().settings().getString(Keys.web.siteName, Constants.NAME));
  211. add(rootLink);
  212. // Feedback panel for info, warning, and non-fatal error messages
  213. add(new FeedbackPanel("feedback"));
  214. add(new Label("gbVersion", "v" + Constants.getVersion()));
  215. if (app().settings().getBoolean(Keys.web.aggressiveHeapManagement, false)) {
  216. System.gc();
  217. }
  218. }
  219. protected Map<AccessRestrictionType, String> getAccessRestrictions() {
  220. Map<AccessRestrictionType, String> map = new LinkedHashMap<AccessRestrictionType, String>();
  221. for (AccessRestrictionType type : AccessRestrictionType.values()) {
  222. switch (type) {
  223. case NONE:
  224. map.put(type, getString("gb.notRestricted"));
  225. break;
  226. case PUSH:
  227. map.put(type, getString("gb.pushRestricted"));
  228. break;
  229. case CLONE:
  230. map.put(type, getString("gb.cloneRestricted"));
  231. break;
  232. case VIEW:
  233. map.put(type, getString("gb.viewRestricted"));
  234. break;
  235. }
  236. }
  237. return map;
  238. }
  239. protected Map<AccessPermission, String> getAccessPermissions() {
  240. Map<AccessPermission, String> map = new LinkedHashMap<AccessPermission, String>();
  241. for (AccessPermission type : AccessPermission.values()) {
  242. switch (type) {
  243. case NONE:
  244. map.put(type, MessageFormat.format(getString("gb.noPermission"), type.code));
  245. break;
  246. case EXCLUDE:
  247. map.put(type, MessageFormat.format(getString("gb.excludePermission"), type.code));
  248. break;
  249. case VIEW:
  250. map.put(type, MessageFormat.format(getString("gb.viewPermission"), type.code));
  251. break;
  252. case CLONE:
  253. map.put(type, MessageFormat.format(getString("gb.clonePermission"), type.code));
  254. break;
  255. case PUSH:
  256. map.put(type, MessageFormat.format(getString("gb.pushPermission"), type.code));
  257. break;
  258. case CREATE:
  259. map.put(type, MessageFormat.format(getString("gb.createPermission"), type.code));
  260. break;
  261. case DELETE:
  262. map.put(type, MessageFormat.format(getString("gb.deletePermission"), type.code));
  263. break;
  264. case REWIND:
  265. map.put(type, MessageFormat.format(getString("gb.rewindPermission"), type.code));
  266. break;
  267. }
  268. }
  269. return map;
  270. }
  271. protected Map<FederationStrategy, String> getFederationTypes() {
  272. Map<FederationStrategy, String> map = new LinkedHashMap<FederationStrategy, String>();
  273. for (FederationStrategy type : FederationStrategy.values()) {
  274. switch (type) {
  275. case EXCLUDE:
  276. map.put(type, getString("gb.excludeFromFederation"));
  277. break;
  278. case FEDERATE_THIS:
  279. map.put(type, getString("gb.federateThis"));
  280. break;
  281. case FEDERATE_ORIGIN:
  282. map.put(type, getString("gb.federateOrigin"));
  283. break;
  284. }
  285. }
  286. return map;
  287. }
  288. protected Map<AuthorizationControl, String> getAuthorizationControls() {
  289. Map<AuthorizationControl, String> map = new LinkedHashMap<AuthorizationControl, String>();
  290. for (AuthorizationControl type : AuthorizationControl.values()) {
  291. switch (type) {
  292. case AUTHENTICATED:
  293. map.put(type, getString("gb.allowAuthenticatedDescription"));
  294. break;
  295. case NAMED:
  296. map.put(type, getString("gb.allowNamedDescription"));
  297. break;
  298. }
  299. }
  300. return map;
  301. }
  302. protected TimeZone getTimeZone() {
  303. return app().settings().getBoolean(Keys.web.useClientTimezone, false) ? GitBlitWebSession.get()
  304. .getTimezone() : app().getTimezone();
  305. }
  306. protected String getServerName() {
  307. ServletWebRequest servletWebRequest = (ServletWebRequest) getRequest();
  308. HttpServletRequest req = servletWebRequest.getHttpServletRequest();
  309. return req.getServerName();
  310. }
  311. protected List<ProjectModel> getProjectModels() {
  312. final UserModel user = GitBlitWebSession.get().getUser();
  313. List<ProjectModel> projects = app().projects().getProjectModels(user, true);
  314. return projects;
  315. }
  316. protected List<ProjectModel> getProjects(PageParameters params) {
  317. if (params == null) {
  318. return getProjectModels();
  319. }
  320. boolean hasParameter = false;
  321. String regex = WicketUtils.getRegEx(params);
  322. String team = WicketUtils.getTeam(params);
  323. int daysBack = params.getInt("db", 0);
  324. int maxDaysBack = app().settings().getInteger(Keys.web.activityDurationMaximum, 30);
  325. List<ProjectModel> availableModels = getProjectModels();
  326. Set<ProjectModel> models = new HashSet<ProjectModel>();
  327. if (!StringUtils.isEmpty(regex)) {
  328. // filter the projects by the regex
  329. hasParameter = true;
  330. Pattern pattern = Pattern.compile(regex);
  331. for (ProjectModel model : availableModels) {
  332. if (pattern.matcher(model.name).find()) {
  333. models.add(model);
  334. }
  335. }
  336. }
  337. if (!StringUtils.isEmpty(team)) {
  338. // filter the projects by the specified teams
  339. hasParameter = true;
  340. List<String> teams = StringUtils.getStringsFromValue(team, ",");
  341. // need TeamModels first
  342. List<TeamModel> teamModels = new ArrayList<TeamModel>();
  343. for (String name : teams) {
  344. TeamModel teamModel = app().users().getTeamModel(name);
  345. if (teamModel != null) {
  346. teamModels.add(teamModel);
  347. }
  348. }
  349. // brute-force our way through finding the matching models
  350. for (ProjectModel projectModel : availableModels) {
  351. for (String repositoryName : projectModel.repositories) {
  352. for (TeamModel teamModel : teamModels) {
  353. if (teamModel.hasRepositoryPermission(repositoryName)) {
  354. models.add(projectModel);
  355. }
  356. }
  357. }
  358. }
  359. }
  360. if (!hasParameter) {
  361. models.addAll(availableModels);
  362. }
  363. // time-filter the list
  364. if (daysBack > 0) {
  365. if (maxDaysBack > 0 && daysBack > maxDaysBack) {
  366. daysBack = maxDaysBack;
  367. }
  368. Calendar cal = Calendar.getInstance();
  369. cal.set(Calendar.HOUR_OF_DAY, 0);
  370. cal.set(Calendar.MINUTE, 0);
  371. cal.set(Calendar.SECOND, 0);
  372. cal.set(Calendar.MILLISECOND, 0);
  373. cal.add(Calendar.DATE, -1 * daysBack);
  374. Date threshold = cal.getTime();
  375. Set<ProjectModel> timeFiltered = new HashSet<ProjectModel>();
  376. for (ProjectModel model : models) {
  377. if (model.lastChange.after(threshold)) {
  378. timeFiltered.add(model);
  379. }
  380. }
  381. models = timeFiltered;
  382. }
  383. List<ProjectModel> list = new ArrayList<ProjectModel>(models);
  384. Collections.sort(list);
  385. return list;
  386. }
  387. public void warn(String message, Throwable t) {
  388. logger().warn(message, t);
  389. }
  390. public void error(String message, boolean redirect) {
  391. error(message, null, redirect ? getApplication().getHomePage() : null);
  392. }
  393. public void error(String message, Throwable t, boolean redirect) {
  394. error(message, t, getApplication().getHomePage());
  395. }
  396. public void error(String message, Throwable t, Class<? extends Page> toPage) {
  397. error(message, t, toPage, null);
  398. }
  399. public void error(String message, Throwable t, Class<? extends Page> toPage, PageParameters params) {
  400. if (t == null) {
  401. logger().error(message + " for " + GitBlitWebSession.get().getUsername());
  402. } else {
  403. logger().error(message + " for " + GitBlitWebSession.get().getUsername(), t);
  404. }
  405. if (toPage != null) {
  406. GitBlitWebSession.get().cacheErrorMessage(message);
  407. String relativeUrl = urlFor(toPage, params).toString();
  408. String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
  409. throw new RedirectToUrlException(absoluteUrl);
  410. } else {
  411. super.error(message);
  412. }
  413. }
  414. public void authenticationError(String message) {
  415. logger().error(getRequest().getURL() + " for " + GitBlitWebSession.get().getUsername());
  416. if (!GitBlitWebSession.get().isLoggedIn()) {
  417. // cache the request if we have not authenticated.
  418. // the request will continue after authentication.
  419. GitBlitWebSession.get().cacheRequest(getClass());
  420. }
  421. error(message, true);
  422. }
  423. protected String readResource(String resource) {
  424. StringBuilder sb = new StringBuilder();
  425. InputStream is = null;
  426. try {
  427. is = getClass().getResourceAsStream(resource);
  428. List<String> lines = IOUtils.readLines(is);
  429. for (String line : lines) {
  430. sb.append(line).append('\n');
  431. }
  432. } catch (IOException e) {
  433. } finally {
  434. if (is != null) {
  435. try {
  436. is.close();
  437. } catch (IOException e) {
  438. }
  439. }
  440. }
  441. return sb.toString();
  442. }
  443. }