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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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.text.MessageFormat;
  18. import java.util.ArrayList;
  19. import java.util.Calendar;
  20. import java.util.Collections;
  21. import java.util.Date;
  22. import java.util.HashSet;
  23. import java.util.LinkedHashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.ResourceBundle;
  27. import java.util.Set;
  28. import java.util.TimeZone;
  29. import java.util.regex.Pattern;
  30. import javax.servlet.http.HttpServletRequest;
  31. import org.apache.wicket.Application;
  32. import org.apache.wicket.MarkupContainer;
  33. import org.apache.wicket.PageParameters;
  34. import org.apache.wicket.RedirectToUrlException;
  35. import org.apache.wicket.RestartResponseException;
  36. import org.apache.wicket.markup.html.CSSPackageResource;
  37. import org.apache.wicket.markup.html.basic.Label;
  38. import org.apache.wicket.markup.html.link.BookmarkablePageLink;
  39. import org.apache.wicket.markup.html.link.ExternalLink;
  40. import org.apache.wicket.markup.html.panel.FeedbackPanel;
  41. import org.apache.wicket.markup.html.panel.Fragment;
  42. import org.apache.wicket.protocol.http.RequestUtils;
  43. import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
  44. import org.slf4j.Logger;
  45. import org.slf4j.LoggerFactory;
  46. import com.gitblit.Constants;
  47. import com.gitblit.Constants.AccessPermission;
  48. import com.gitblit.Constants.AccessRestrictionType;
  49. import com.gitblit.Constants.AuthorizationControl;
  50. import com.gitblit.Constants.FederationStrategy;
  51. import com.gitblit.GitBlit;
  52. import com.gitblit.Keys;
  53. import com.gitblit.models.ProjectModel;
  54. import com.gitblit.models.TeamModel;
  55. import com.gitblit.models.UserModel;
  56. import com.gitblit.utils.StringUtils;
  57. import com.gitblit.utils.TimeUtils;
  58. import com.gitblit.wicket.GitBlitWebSession;
  59. import com.gitblit.wicket.WicketUtils;
  60. import com.gitblit.wicket.panels.LinkPanel;
  61. public abstract class BasePage extends SessionPage {
  62. private final Logger logger;
  63. private transient TimeUtils timeUtils;
  64. public BasePage() {
  65. super();
  66. logger = LoggerFactory.getLogger(getClass());
  67. customizeHeader();
  68. }
  69. public BasePage(PageParameters params) {
  70. super(params);
  71. logger = LoggerFactory.getLogger(getClass());
  72. customizeHeader();
  73. }
  74. private void customizeHeader() {
  75. if (GitBlit.getBoolean(Keys.web.useResponsiveLayout, true)) {
  76. add(CSSPackageResource.getHeaderContribution("bootstrap/css/bootstrap-responsive.css"));
  77. }
  78. }
  79. protected String getLanguageCode() {
  80. return GitBlitWebSession.get().getLocale().getLanguage();
  81. }
  82. protected String getCountryCode() {
  83. return GitBlitWebSession.get().getLocale().getCountry().toLowerCase();
  84. }
  85. protected TimeUtils getTimeUtils() {
  86. if (timeUtils == null) {
  87. ResourceBundle bundle;
  88. try {
  89. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp", GitBlitWebSession.get().getLocale());
  90. } catch (Throwable t) {
  91. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp");
  92. }
  93. timeUtils = new TimeUtils(bundle);
  94. }
  95. return timeUtils;
  96. }
  97. @Override
  98. protected void onBeforeRender() {
  99. if (GitBlit.isDebugMode()) {
  100. // strip Wicket tags in debug mode for jQuery DOM traversal
  101. Application.get().getMarkupSettings().setStripWicketTags(true);
  102. }
  103. super.onBeforeRender();
  104. }
  105. @Override
  106. protected void onAfterRender() {
  107. if (GitBlit.isDebugMode()) {
  108. // restore Wicket debug tags
  109. Application.get().getMarkupSettings().setStripWicketTags(false);
  110. }
  111. super.onAfterRender();
  112. }
  113. protected void setupPage(String repositoryName, String pageName) {
  114. String siteName = GitBlit.getString(Keys.web.siteName, Constants.NAME);
  115. if (repositoryName != null && repositoryName.trim().length() > 0) {
  116. add(new Label("title", repositoryName + " - " + siteName));
  117. } else {
  118. add(new Label("title", siteName));
  119. }
  120. ExternalLink rootLink = new ExternalLink("rootLink", urlFor(RepositoriesPage.class, null).toString());
  121. WicketUtils.setHtmlTooltip(rootLink, siteName);
  122. add(rootLink);
  123. // Feedback panel for info, warning, and non-fatal error messages
  124. add(new FeedbackPanel("feedback"));
  125. // footer
  126. if (GitBlit.getBoolean(Keys.web.authenticateViewPages, true)
  127. || GitBlit.getBoolean(Keys.web.authenticateAdminPages, true)) {
  128. UserFragment userFragment = new UserFragment("userPanel", "userFragment", BasePage.this);
  129. add(userFragment);
  130. } else {
  131. add(new Label("userPanel", ""));
  132. }
  133. add(new Label("gbVersion", "v" + Constants.getVersion()));
  134. if (GitBlit.getBoolean(Keys.web.aggressiveHeapManagement, false)) {
  135. System.gc();
  136. }
  137. }
  138. protected Map<AccessRestrictionType, String> getAccessRestrictions() {
  139. Map<AccessRestrictionType, String> map = new LinkedHashMap<AccessRestrictionType, String>();
  140. for (AccessRestrictionType type : AccessRestrictionType.values()) {
  141. switch (type) {
  142. case NONE:
  143. map.put(type, getString("gb.notRestricted"));
  144. break;
  145. case PUSH:
  146. map.put(type, getString("gb.pushRestricted"));
  147. break;
  148. case CLONE:
  149. map.put(type, getString("gb.cloneRestricted"));
  150. break;
  151. case VIEW:
  152. map.put(type, getString("gb.viewRestricted"));
  153. break;
  154. }
  155. }
  156. return map;
  157. }
  158. protected Map<AccessPermission, String> getAccessPermissions() {
  159. Map<AccessPermission, String> map = new LinkedHashMap<AccessPermission, String>();
  160. for (AccessPermission type : AccessPermission.values()) {
  161. switch (type) {
  162. case NONE:
  163. map.put(type, MessageFormat.format(getString("gb.noPermission"), type.code));
  164. break;
  165. case EXCLUDE:
  166. map.put(type, MessageFormat.format(getString("gb.excludePermission"), type.code));
  167. break;
  168. case VIEW:
  169. map.put(type, MessageFormat.format(getString("gb.viewPermission"), type.code));
  170. break;
  171. case CLONE:
  172. map.put(type, MessageFormat.format(getString("gb.clonePermission"), type.code));
  173. break;
  174. case PUSH:
  175. map.put(type, MessageFormat.format(getString("gb.pushPermission"), type.code));
  176. break;
  177. case CREATE:
  178. map.put(type, MessageFormat.format(getString("gb.createPermission"), type.code));
  179. break;
  180. case DELETE:
  181. map.put(type, MessageFormat.format(getString("gb.deletePermission"), type.code));
  182. break;
  183. case REWIND:
  184. map.put(type, MessageFormat.format(getString("gb.rewindPermission"), type.code));
  185. break;
  186. }
  187. }
  188. return map;
  189. }
  190. protected Map<FederationStrategy, String> getFederationTypes() {
  191. Map<FederationStrategy, String> map = new LinkedHashMap<FederationStrategy, String>();
  192. for (FederationStrategy type : FederationStrategy.values()) {
  193. switch (type) {
  194. case EXCLUDE:
  195. map.put(type, getString("gb.excludeFromFederation"));
  196. break;
  197. case FEDERATE_THIS:
  198. map.put(type, getString("gb.federateThis"));
  199. break;
  200. case FEDERATE_ORIGIN:
  201. map.put(type, getString("gb.federateOrigin"));
  202. break;
  203. }
  204. }
  205. return map;
  206. }
  207. protected Map<AuthorizationControl, String> getAuthorizationControls() {
  208. Map<AuthorizationControl, String> map = new LinkedHashMap<AuthorizationControl, String>();
  209. for (AuthorizationControl type : AuthorizationControl.values()) {
  210. switch (type) {
  211. case AUTHENTICATED:
  212. map.put(type, getString("gb.allowAuthenticatedDescription"));
  213. break;
  214. case NAMED:
  215. map.put(type, getString("gb.allowNamedDescription"));
  216. break;
  217. }
  218. }
  219. return map;
  220. }
  221. protected TimeZone getTimeZone() {
  222. return GitBlit.getBoolean(Keys.web.useClientTimezone, false) ? GitBlitWebSession.get()
  223. .getTimezone() : GitBlit.getTimezone();
  224. }
  225. protected String getServerName() {
  226. ServletWebRequest servletWebRequest = (ServletWebRequest) getRequest();
  227. HttpServletRequest req = servletWebRequest.getHttpServletRequest();
  228. return req.getServerName();
  229. }
  230. protected List<ProjectModel> getProjectModels() {
  231. final UserModel user = GitBlitWebSession.get().getUser();
  232. List<ProjectModel> projects = GitBlit.self().getProjectModels(user, true);
  233. return projects;
  234. }
  235. protected List<ProjectModel> getProjects(PageParameters params) {
  236. if (params == null) {
  237. return getProjectModels();
  238. }
  239. boolean hasParameter = false;
  240. String regex = WicketUtils.getRegEx(params);
  241. String team = WicketUtils.getTeam(params);
  242. int daysBack = params.getInt("db", 0);
  243. List<ProjectModel> availableModels = getProjectModels();
  244. Set<ProjectModel> models = new HashSet<ProjectModel>();
  245. if (!StringUtils.isEmpty(regex)) {
  246. // filter the projects by the regex
  247. hasParameter = true;
  248. Pattern pattern = Pattern.compile(regex);
  249. for (ProjectModel model : availableModels) {
  250. if (pattern.matcher(model.name).find()) {
  251. models.add(model);
  252. }
  253. }
  254. }
  255. if (!StringUtils.isEmpty(team)) {
  256. // filter the projects by the specified teams
  257. hasParameter = true;
  258. List<String> teams = StringUtils.getStringsFromValue(team, ",");
  259. // need TeamModels first
  260. List<TeamModel> teamModels = new ArrayList<TeamModel>();
  261. for (String name : teams) {
  262. TeamModel teamModel = GitBlit.self().getTeamModel(name);
  263. if (teamModel != null) {
  264. teamModels.add(teamModel);
  265. }
  266. }
  267. // brute-force our way through finding the matching models
  268. for (ProjectModel projectModel : availableModels) {
  269. for (String repositoryName : projectModel.repositories) {
  270. for (TeamModel teamModel : teamModels) {
  271. if (teamModel.hasRepositoryPermission(repositoryName)) {
  272. models.add(projectModel);
  273. }
  274. }
  275. }
  276. }
  277. }
  278. if (!hasParameter) {
  279. models.addAll(availableModels);
  280. }
  281. // time-filter the list
  282. if (daysBack > 0) {
  283. Calendar cal = Calendar.getInstance();
  284. cal.set(Calendar.HOUR_OF_DAY, 0);
  285. cal.set(Calendar.MINUTE, 0);
  286. cal.set(Calendar.SECOND, 0);
  287. cal.set(Calendar.MILLISECOND, 0);
  288. cal.add(Calendar.DATE, -1 * daysBack);
  289. Date threshold = cal.getTime();
  290. Set<ProjectModel> timeFiltered = new HashSet<ProjectModel>();
  291. for (ProjectModel model : models) {
  292. if (model.lastChange.after(threshold)) {
  293. timeFiltered.add(model);
  294. }
  295. }
  296. models = timeFiltered;
  297. }
  298. List<ProjectModel> list = new ArrayList<ProjectModel>(models);
  299. Collections.sort(list);
  300. return list;
  301. }
  302. public void warn(String message, Throwable t) {
  303. logger.warn(message, t);
  304. }
  305. public void error(String message, boolean redirect) {
  306. logger.error(message + " for " + GitBlitWebSession.get().getUsername());
  307. if (redirect) {
  308. GitBlitWebSession.get().cacheErrorMessage(message);
  309. String relativeUrl = urlFor(RepositoriesPage.class, null).toString();
  310. String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
  311. throw new RedirectToUrlException(absoluteUrl);
  312. } else {
  313. super.error(message);
  314. }
  315. }
  316. public void error(String message, Throwable t, boolean redirect) {
  317. logger.error(message, t);
  318. if (redirect) {
  319. GitBlitWebSession.get().cacheErrorMessage(message);
  320. throw new RestartResponseException(getApplication().getHomePage());
  321. } else {
  322. super.error(message);
  323. }
  324. }
  325. public void authenticationError(String message) {
  326. logger.error(getRequest().getURL() + " for " + GitBlitWebSession.get().getUsername());
  327. if (!GitBlitWebSession.get().isLoggedIn()) {
  328. // cache the request if we have not authenticated.
  329. // the request will continue after authentication.
  330. GitBlitWebSession.get().cacheRequest(getClass());
  331. }
  332. error(message, true);
  333. }
  334. /**
  335. * Panel fragment for displaying login or logout/change_password links.
  336. *
  337. */
  338. static class UserFragment extends Fragment {
  339. private static final long serialVersionUID = 1L;
  340. public UserFragment(String id, String markupId, MarkupContainer markupProvider) {
  341. super(id, markupId, markupProvider);
  342. GitBlitWebSession session = GitBlitWebSession.get();
  343. if (session.isLoggedIn()) {
  344. UserModel user = session.getUser();
  345. boolean editCredentials = GitBlit.self().supportsCredentialChanges(user);
  346. boolean standardLogin = session.authenticationType.isStandard();
  347. // username, logout, and change password
  348. add(new Label("username", user.getDisplayName() + ":"));
  349. add(new LinkPanel("loginLink", null, markupProvider.getString("gb.logout"),
  350. LogoutPage.class).setVisible(standardLogin));
  351. // quick and dirty hack for showing a separator
  352. add(new Label("separator", "|").setVisible(standardLogin && editCredentials));
  353. add(new BookmarkablePageLink<Void>("changePasswordLink",
  354. ChangePasswordPage.class).setVisible(editCredentials));
  355. } else {
  356. // login
  357. add(new Label("username").setVisible(false));
  358. add(new Label("loginLink").setVisible(false));
  359. add(new Label("separator").setVisible(false));
  360. add(new Label("changePasswordLink").setVisible(false));
  361. }
  362. }
  363. }
  364. }