選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

BasePage.java 18KB

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