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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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 getCanonicalUrl() {
  90. return getCanonicalUrl(getClass(), getPageParameters());
  91. }
  92. protected String getCanonicalUrl(Class<? extends BasePage> clazz, PageParameters params) {
  93. String relativeUrl = urlFor(clazz, params).toString();
  94. String canonicalUrl = RequestUtils.toAbsolutePath(relativeUrl);
  95. return canonicalUrl;
  96. }
  97. protected String getLanguageCode() {
  98. return GitBlitWebSession.get().getLocale().getLanguage();
  99. }
  100. protected String getCountryCode() {
  101. return GitBlitWebSession.get().getLocale().getCountry().toLowerCase();
  102. }
  103. protected TimeUtils getTimeUtils() {
  104. if (timeUtils == null) {
  105. ResourceBundle bundle;
  106. try {
  107. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp", GitBlitWebSession.get().getLocale());
  108. } catch (Throwable t) {
  109. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp");
  110. }
  111. timeUtils = new TimeUtils(bundle, getTimeZone());
  112. }
  113. return timeUtils;
  114. }
  115. @Override
  116. protected void onBeforeRender() {
  117. if (app().isDebugMode()) {
  118. // strip Wicket tags in debug mode for jQuery DOM traversal
  119. Application.get().getMarkupSettings().setStripWicketTags(true);
  120. }
  121. super.onBeforeRender();
  122. }
  123. @Override
  124. protected void onAfterRender() {
  125. if (app().isDebugMode()) {
  126. // restore Wicket debug tags
  127. Application.get().getMarkupSettings().setStripWicketTags(false);
  128. }
  129. super.onAfterRender();
  130. }
  131. @Override
  132. protected void setHeaders(WebResponse response) {
  133. // set canonical link as http header for SEO (issue-304)
  134. // https://support.google.com/webmasters/answer/139394?hl=en
  135. response.setHeader("Link", MessageFormat.format("<{0}>; rel=\"canonical\"", getCanonicalUrl()));
  136. int expires = app().settings().getInteger(Keys.web.pageCacheExpires, 0);
  137. if (expires > 0) {
  138. // pages are personalized for the authenticated user so they must be
  139. // marked private to prohibit proxy servers from caching them
  140. response.setHeader("Cache-Control", "private, must-revalidate");
  141. setLastModified();
  142. } else {
  143. // use default Wicket caching behavior
  144. super.setHeaders(response);
  145. }
  146. }
  147. /**
  148. * Sets the last-modified header date, if appropriate, for this page. The
  149. * date used is determined by the CacheControl annotation.
  150. *
  151. */
  152. protected void setLastModified() {
  153. if (getClass().isAnnotationPresent(CacheControl.class)) {
  154. CacheControl cacheControl = getClass().getAnnotation(CacheControl.class);
  155. switch (cacheControl.value()) {
  156. case ACTIVITY:
  157. setLastModified(app().getLastActivityDate());
  158. break;
  159. case BOOT:
  160. setLastModified(app().getBootDate());
  161. break;
  162. case NONE:
  163. break;
  164. default:
  165. logger().warn(getClass().getSimpleName() + ": unhandled LastModified type " + cacheControl.value());
  166. break;
  167. }
  168. }
  169. }
  170. /**
  171. * Sets the last-modified header field and the expires field.
  172. *
  173. * @param when
  174. */
  175. protected final void setLastModified(Date when) {
  176. if (when == null) {
  177. return;
  178. }
  179. if (when.before(app().getBootDate())) {
  180. // last-modified can not be before the Gitblit boot date
  181. // this helps ensure that pages are properly refreshed after a
  182. // server config change
  183. when = app().getBootDate();
  184. }
  185. int expires = app().settings().getInteger(Keys.web.pageCacheExpires, 0);
  186. WebResponse response = (WebResponse) getResponse();
  187. response.setLastModifiedTime(Time.valueOf(when));
  188. response.setDateHeader("Expires", System.currentTimeMillis() + Duration.minutes(expires).getMilliseconds());
  189. }
  190. protected String getPageTitle(String repositoryName) {
  191. String siteName = app().settings().getString(Keys.web.siteName, Constants.NAME);
  192. if (StringUtils.isEmpty(siteName)) {
  193. siteName = Constants.NAME;
  194. }
  195. if (repositoryName != null && repositoryName.trim().length() > 0) {
  196. return repositoryName + " - " + siteName;
  197. } else {
  198. return siteName;
  199. }
  200. }
  201. protected void setupPage(String repositoryName, String pageName) {
  202. add(new Label("title", getPageTitle(repositoryName)));
  203. String rootLinkUrl = app().settings().getString(Keys.web.rootLink, urlFor(GitBlitWebApp.get().getHomePage(), null).toString());
  204. ExternalLink rootLink = new ExternalLink("rootLink", rootLinkUrl);
  205. WicketUtils.setHtmlTooltip(rootLink, app().settings().getString(Keys.web.siteName, Constants.NAME));
  206. add(rootLink);
  207. // Feedback panel for info, warning, and non-fatal error messages
  208. add(new FeedbackPanel("feedback"));
  209. add(new Label("gbVersion", "v" + Constants.getVersion()));
  210. if (app().settings().getBoolean(Keys.web.aggressiveHeapManagement, false)) {
  211. System.gc();
  212. }
  213. }
  214. protected Map<AccessRestrictionType, String> getAccessRestrictions() {
  215. Map<AccessRestrictionType, String> map = new LinkedHashMap<AccessRestrictionType, String>();
  216. for (AccessRestrictionType type : AccessRestrictionType.values()) {
  217. switch (type) {
  218. case NONE:
  219. map.put(type, getString("gb.notRestricted"));
  220. break;
  221. case PUSH:
  222. map.put(type, getString("gb.pushRestricted"));
  223. break;
  224. case CLONE:
  225. map.put(type, getString("gb.cloneRestricted"));
  226. break;
  227. case VIEW:
  228. map.put(type, getString("gb.viewRestricted"));
  229. break;
  230. }
  231. }
  232. return map;
  233. }
  234. protected Map<AccessPermission, String> getAccessPermissions() {
  235. Map<AccessPermission, String> map = new LinkedHashMap<AccessPermission, String>();
  236. for (AccessPermission type : AccessPermission.values()) {
  237. switch (type) {
  238. case NONE:
  239. map.put(type, MessageFormat.format(getString("gb.noPermission"), type.code));
  240. break;
  241. case EXCLUDE:
  242. map.put(type, MessageFormat.format(getString("gb.excludePermission"), type.code));
  243. break;
  244. case VIEW:
  245. map.put(type, MessageFormat.format(getString("gb.viewPermission"), type.code));
  246. break;
  247. case CLONE:
  248. map.put(type, MessageFormat.format(getString("gb.clonePermission"), type.code));
  249. break;
  250. case PUSH:
  251. map.put(type, MessageFormat.format(getString("gb.pushPermission"), type.code));
  252. break;
  253. case CREATE:
  254. map.put(type, MessageFormat.format(getString("gb.createPermission"), type.code));
  255. break;
  256. case DELETE:
  257. map.put(type, MessageFormat.format(getString("gb.deletePermission"), type.code));
  258. break;
  259. case REWIND:
  260. map.put(type, MessageFormat.format(getString("gb.rewindPermission"), type.code));
  261. break;
  262. }
  263. }
  264. return map;
  265. }
  266. protected Map<FederationStrategy, String> getFederationTypes() {
  267. Map<FederationStrategy, String> map = new LinkedHashMap<FederationStrategy, String>();
  268. for (FederationStrategy type : FederationStrategy.values()) {
  269. switch (type) {
  270. case EXCLUDE:
  271. map.put(type, getString("gb.excludeFromFederation"));
  272. break;
  273. case FEDERATE_THIS:
  274. map.put(type, getString("gb.federateThis"));
  275. break;
  276. case FEDERATE_ORIGIN:
  277. map.put(type, getString("gb.federateOrigin"));
  278. break;
  279. }
  280. }
  281. return map;
  282. }
  283. protected Map<AuthorizationControl, String> getAuthorizationControls() {
  284. Map<AuthorizationControl, String> map = new LinkedHashMap<AuthorizationControl, String>();
  285. for (AuthorizationControl type : AuthorizationControl.values()) {
  286. switch (type) {
  287. case AUTHENTICATED:
  288. map.put(type, getString("gb.allowAuthenticatedDescription"));
  289. break;
  290. case NAMED:
  291. map.put(type, getString("gb.allowNamedDescription"));
  292. break;
  293. }
  294. }
  295. return map;
  296. }
  297. protected TimeZone getTimeZone() {
  298. return app().settings().getBoolean(Keys.web.useClientTimezone, false) ? GitBlitWebSession.get()
  299. .getTimezone() : app().getTimezone();
  300. }
  301. protected String getServerName() {
  302. ServletWebRequest servletWebRequest = (ServletWebRequest) getRequest();
  303. HttpServletRequest req = servletWebRequest.getHttpServletRequest();
  304. return req.getServerName();
  305. }
  306. protected List<ProjectModel> getProjectModels() {
  307. final UserModel user = GitBlitWebSession.get().getUser();
  308. List<ProjectModel> projects = app().projects().getProjectModels(user, true);
  309. return projects;
  310. }
  311. protected List<ProjectModel> getProjects(PageParameters params) {
  312. if (params == null) {
  313. return getProjectModels();
  314. }
  315. boolean hasParameter = false;
  316. String regex = WicketUtils.getRegEx(params);
  317. String team = WicketUtils.getTeam(params);
  318. int daysBack = params.getInt("db", 0);
  319. int maxDaysBack = app().settings().getInteger(Keys.web.activityDurationMaximum, 30);
  320. List<ProjectModel> availableModels = getProjectModels();
  321. Set<ProjectModel> models = new HashSet<ProjectModel>();
  322. if (!StringUtils.isEmpty(regex)) {
  323. // filter the projects by the regex
  324. hasParameter = true;
  325. Pattern pattern = Pattern.compile(regex);
  326. for (ProjectModel model : availableModels) {
  327. if (pattern.matcher(model.name).find()) {
  328. models.add(model);
  329. }
  330. }
  331. }
  332. if (!StringUtils.isEmpty(team)) {
  333. // filter the projects by the specified teams
  334. hasParameter = true;
  335. List<String> teams = StringUtils.getStringsFromValue(team, ",");
  336. // need TeamModels first
  337. List<TeamModel> teamModels = new ArrayList<TeamModel>();
  338. for (String name : teams) {
  339. TeamModel teamModel = app().users().getTeamModel(name);
  340. if (teamModel != null) {
  341. teamModels.add(teamModel);
  342. }
  343. }
  344. // brute-force our way through finding the matching models
  345. for (ProjectModel projectModel : availableModels) {
  346. for (String repositoryName : projectModel.repositories) {
  347. for (TeamModel teamModel : teamModels) {
  348. if (teamModel.hasRepositoryPermission(repositoryName)) {
  349. models.add(projectModel);
  350. }
  351. }
  352. }
  353. }
  354. }
  355. if (!hasParameter) {
  356. models.addAll(availableModels);
  357. }
  358. // time-filter the list
  359. if (daysBack > 0) {
  360. if (maxDaysBack > 0 && daysBack > maxDaysBack) {
  361. daysBack = maxDaysBack;
  362. }
  363. Calendar cal = Calendar.getInstance();
  364. cal.set(Calendar.HOUR_OF_DAY, 0);
  365. cal.set(Calendar.MINUTE, 0);
  366. cal.set(Calendar.SECOND, 0);
  367. cal.set(Calendar.MILLISECOND, 0);
  368. cal.add(Calendar.DATE, -1 * daysBack);
  369. Date threshold = cal.getTime();
  370. Set<ProjectModel> timeFiltered = new HashSet<ProjectModel>();
  371. for (ProjectModel model : models) {
  372. if (model.lastChange.after(threshold)) {
  373. timeFiltered.add(model);
  374. }
  375. }
  376. models = timeFiltered;
  377. }
  378. List<ProjectModel> list = new ArrayList<ProjectModel>(models);
  379. Collections.sort(list);
  380. return list;
  381. }
  382. public void warn(String message, Throwable t) {
  383. logger().warn(message, t);
  384. }
  385. public void error(String message, boolean redirect) {
  386. error(message, null, redirect ? getApplication().getHomePage() : null);
  387. }
  388. public void error(String message, Throwable t, boolean redirect) {
  389. error(message, t, getApplication().getHomePage());
  390. }
  391. public void error(String message, Throwable t, Class<? extends Page> toPage) {
  392. error(message, t, toPage, null);
  393. }
  394. public void error(String message, Throwable t, Class<? extends Page> toPage, PageParameters params) {
  395. if (t == null) {
  396. logger().error(message + " for " + GitBlitWebSession.get().getUsername());
  397. } else {
  398. logger().error(message + " for " + GitBlitWebSession.get().getUsername(), t);
  399. }
  400. if (toPage != null) {
  401. GitBlitWebSession.get().cacheErrorMessage(message);
  402. String relativeUrl = urlFor(toPage, params).toString();
  403. String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
  404. throw new RedirectToUrlException(absoluteUrl);
  405. } else {
  406. super.error(message);
  407. }
  408. }
  409. public void authenticationError(String message) {
  410. logger().error(getRequest().getURL() + " for " + GitBlitWebSession.get().getUsername());
  411. if (!GitBlitWebSession.get().isLoggedIn()) {
  412. // cache the request if we have not authenticated.
  413. // the request will continue after authentication.
  414. GitBlitWebSession.get().cacheRequest(getClass());
  415. }
  416. error(message, true);
  417. }
  418. protected String readResource(String resource) {
  419. StringBuilder sb = new StringBuilder();
  420. InputStream is = null;
  421. try {
  422. is = getClass().getResourceAsStream(resource);
  423. List<String> lines = IOUtils.readLines(is);
  424. for (String line : lines) {
  425. sb.append(line).append('\n');
  426. }
  427. } catch (IOException e) {
  428. } finally {
  429. if (is != null) {
  430. try {
  431. is.close();
  432. } catch (IOException e) {
  433. }
  434. }
  435. }
  436. return sb.toString();
  437. }
  438. }