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

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