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

application_controller.rb 30 kB

13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
13 years ago
13 years ago
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
12 years ago
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
13 years ago
13 years ago
​
​
​
​
​
​
12 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
13 years ago
​
12 years ago
12 years ago
13 years ago
​
​
​
​
​
​
​
​
​
​
12 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
13 years ago
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
13 years ago
​
​
​
13 years ago
​
13 years ago
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
12 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. require 'uri'
  18. require 'cgi'
  19. class Unauthorized < Exception; end
  20. class ApplicationController < ActionController::Base
  21. include Redmine::I18n
  22. include Redmine::Pagination
  23. include RoutesHelper
  24. helper :routes
  25. #added by william
  26. helper :watchers
  27. class_attribute :accept_api_auth_actions
  28. class_attribute :accept_rss_auth_actions
  29. class_attribute :model_object
  30. layout 'base'
  31. protect_from_forgery
  32. def handle_unverified_request
  33. super
  34. raise(ActionController::InvalidAuthenticityToken)
  35. # cookies.delete(autologin_cookie_name)
  36. end
  37. before_filter :find_first_page
  38. before_filter :find_web_footer
  39. before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
  40. before_filter :user_agent
  41. rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
  42. rescue_from ::Unauthorized, :with => :deny_access
  43. rescue_from ::ActionView::MissingTemplate, :with => :missing_template
  44. include Redmine::Search::Controller
  45. include Redmine::MenuManager::MenuController
  46. helper Redmine::MenuManager::MenuHelper
  47. def user_agent
  48. logger.info "HTTP_USER_AGENT #{request.env["HTTP_USER_AGENT"]}"
  49. end
  50. def session_expiration
  51. if session[:user_id]
  52. if session_expired? && !try_to_autologin
  53. reset_session
  54. flash[:error] = l(:error_session_expired)
  55. redirect_to signin_url
  56. else
  57. session[:atime] = Time.now.utc.to_i
  58. end
  59. end
  60. end
  61. def session_expired?
  62. if Setting.session_lifetime?
  63. unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
  64. return true
  65. end
  66. end
  67. if Setting.session_timeout?
  68. unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
  69. return true
  70. end
  71. end
  72. false
  73. end
  74. def start_user_session(user)
  75. session[:user_id] = user.id
  76. session[:ctime] = Time.now.utc.to_i
  77. session[:atime] = Time.now.utc.to_i
  78. end
  79. def user_setup
  80. # Check the settings cache for each request
  81. Setting.check_cache
  82. # Find the current user
  83. User.current = find_current_user
  84. #logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
  85. end
  86. # Returns the current user or nil if no user is logged in
  87. # and starts a session if needed
  88. def current_user
  89. find_current_user
  90. end
  91. def find_current_user
  92. user = nil
  93. unless api_request?
  94. if session[:user_id]
  95. # existing session
  96. user = (User.active.find(session[:user_id]) rescue nil)
  97. elsif autologin_user = try_to_autologin
  98. user = autologin_user
  99. elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
  100. # RSS key authentication does not start a session
  101. user = User.find_by_rss_key(params[:key])
  102. end
  103. end
  104. if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
  105. if (key = api_key_from_request)
  106. # Use API key
  107. user = User.find_by_api_key(key)
  108. else
  109. # HTTP Basic, either username/password or API key/random
  110. authenticate_with_http_basic do |username, password|
  111. user = User.try_to_login(username, password)[0] || User.find_by_api_key(username)
  112. end
  113. end
  114. # Switch user if requested by an admin user
  115. if user && user.admin? && (username = api_switch_user_from_request)
  116. su = User.find_by_login(username)
  117. if su && su.active?
  118. logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
  119. user = su
  120. else
  121. render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
  122. end
  123. end
  124. end
  125. user
  126. end
  127. def autologin_cookie_name
  128. Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
  129. end
  130. def try_to_autologin
  131. if cookies[autologin_cookie_name] && Setting.autologin?
  132. # auto-login feature starts a new session
  133. user = User.try_to_autologin(cookies[autologin_cookie_name])
  134. if user
  135. reset_session
  136. start_user_session(user)
  137. end
  138. user
  139. end
  140. end
  141. def try_to_autologin1
  142. user = User.try_to_autologin(params[:token])
  143. if user
  144. logout_user if User.current.id != user.id
  145. start_user_session(user)
  146. end
  147. user
  148. end
  149. # Sets the logged in user
  150. def logged_user=(user)
  151. reset_session
  152. if user && user.is_a?(User)
  153. User.current = user
  154. start_user_session(user)
  155. else
  156. User.current = User.anonymous
  157. end
  158. end
  159. def logged_user_by_apptoken
  160. #从手机端传来apptoken则将当前登陆用户变为对应的用户
  161. if params[:apptoken]
  162. token = ApiKey.where(access_token: params[:apptoken]).first
  163. if token.expired?
  164. return
  165. end
  166. if token && !token.expired?
  167. @current_user = User.find(token.user_id)
  168. end
  169. unless @current_user.nil?
  170. self.logged_user = @current_user
  171. if @current_user
  172. @current_user.update_column(:last_login_on, Time.now)
  173. end
  174. end
  175. end
  176. end
  177. # Logs out current user
  178. def logout_user
  179. if User.current.logged?
  180. if Redmine::Configuration['cookie_domain'].present?
  181. cookies.delete(autologin_cookie_name, domain: Redmine::Configuration['cookie_domain'])
  182. else
  183. cookies.delete autologin_cookie_name
  184. end
  185. # Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
  186. self.logged_user = nil
  187. end
  188. end
  189. # check if login is globally required to access the application
  190. def check_if_login_required
  191. # no check needed if user is already logged in
  192. return true if User.current.logged?
  193. require_login if Setting.login_required?
  194. end
  195. def set_localization
  196. lang = nil
  197. if User.current.logged?
  198. lang = find_language(User.current.language)
  199. end
  200. if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
  201. accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
  202. if !accept_lang.blank?
  203. accept_lang = accept_lang.downcase
  204. lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
  205. end
  206. end
  207. lang ||= Setting.default_language
  208. set_language_if_valid(lang)
  209. end
  210. def require_login
  211. if !User.current.logged?
  212. # Extract only the basic url parameters on non-GET requests
  213. if request.get?
  214. url = url_for(params)
  215. else
  216. url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
  217. end
  218. respond_to do |format|
  219. format.html { redirect_to signin_url }
  220. format.atom { redirect_to signin_url }
  221. format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  222. format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  223. format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
  224. end
  225. return false
  226. end
  227. true
  228. end
  229. def require_admin
  230. return unless require_login
  231. if !User.current.admin?
  232. render_403
  233. return false
  234. end
  235. true
  236. end
  237. def deny_access
  238. User.current.logged? ? render_403 : require_login
  239. end
  240. # Authorize the user for the requested action
  241. def authorize(ctrl = params[:controller], action = params[:action], global = false)
  242. #modify by NWB
  243. allowed = authorize_allowed(params[:controller], params[:action],global)
  244. if allowed
  245. true
  246. else
  247. if @project && @project.archived?
  248. render_403 :message => :notice_not_authorized_archived_project
  249. else
  250. deny_access
  251. end
  252. end
  253. end
  254. def authorize1(ctrl = params[:controller], action = params[:action],token = params[:token], global = false)
  255. if(!User.current.logged? && !token.nil?)
  256. User.current =try_to_autologin1
  257. end
  258. allowed = authorize_allowed(params[:controller], params[:action],global)
  259. if allowed
  260. true
  261. else
  262. if @project && @project.archived?
  263. render_403 :message => :notice_not_authorized_archived_project
  264. else
  265. deny_access
  266. end
  267. end
  268. end
  269. def auth_login1(token = params[:token])
  270. if(!User.current.logged? && !token.nil?)
  271. User.current =try_to_autologin1
  272. end
  273. end
  274. def authorize_allowed(ctrl = params[:controller], action = params[:action], global = false)
  275. #modify by NWB
  276. if @project
  277. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  278. elsif @course
  279. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @course || @courses, :global => global)
  280. else
  281. # allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
  282. allowed = true
  283. end
  284. allowed
  285. end
  286. def authorize_attachment_download(ctrl = params[:controller], action = params[:action], global = false)
  287. case @attachment.container_type
  288. when "Memo"
  289. allowed = User.current.allowed_to?(:memos_attachments_download,nil,:global => true)
  290. when "Message"
  291. if @project
  292. allowed = User.current.allowed_to?(:projects_attachments_download,@project,:global => false)
  293. elsif @course
  294. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  295. end
  296. when "contest"
  297. return true
  298. when "Course"
  299. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  300. else
  301. return true
  302. end
  303. if allowed
  304. true
  305. else
  306. if @project && @project.archived?
  307. render_403 :message => :notice_not_authorized_archived_project
  308. else
  309. deny_access
  310. end
  311. end
  312. end
  313. def authorize_attachment_download1(ctrl = params[:controller], action = params[:action],token = params[:token], global = false)
  314. if(!User.current.logged? && !token.nil?)
  315. User.current = try_to_autologin1
  316. end
  317. case @attachment.container_type
  318. when "Memo"
  319. allowed = User.current.allowed_to?(:memos_attachments_download,nil,:global => true)
  320. when "Message"
  321. if @project
  322. allowed = User.current.allowed_to?(:projects_attachments_download,@project,:global => false)
  323. elsif @course
  324. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  325. end
  326. when "contest"
  327. return true
  328. when "Course"
  329. if @attachment.get_status_by_attach(User.current.id) == 2
  330. return true
  331. else
  332. allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
  333. end
  334. else
  335. return true
  336. end
  337. if allowed
  338. true
  339. else
  340. if @project && @project.archived?
  341. render_403 :message => :notice_not_authorized_archived_project
  342. else
  343. deny_access
  344. end
  345. end
  346. end
  347. def authorize_course(ctrl = params[:controller], action = params[:action], global = false)
  348. allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @course || @course, :global => global)
  349. if allowed
  350. true
  351. else
  352. if params[:action] == 'show'
  353. #更新申请结果反馈消息的状态
  354. messages = CourseMessage.where("course_message_type =? and course_id =? and user_id =? and viewed =?", 'CourseRequestDealResult', @course.id, User.current.id, false)
  355. messages.update_all(:viewed => true)
  356. end
  357. if @course && @course.archived?
  358. render_403 :message => :notice_not_authorized_archived_project
  359. else
  360. deny_access
  361. end
  362. end
  363. end
  364. def authorize_course_global(ctrl = params[:controller], action = params[:action], global = true)
  365. authorize_course(ctrl, action, global)
  366. end
  367. # Authorize the user for the requested action outside a project
  368. def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
  369. authorize(ctrl, action, global)
  370. end
  371. # Find project of id params[:id]
  372. def find_project
  373. @project = Project.find(params[:id])
  374. rescue ActiveRecord::RecordNotFound
  375. render_404
  376. end
  377. # Find project of id params[:project_id]
  378. def find_project_by_project_id
  379. if params[:project_id]
  380. @project = Project.find(params[:project_id])
  381. elsif params[:course_id]
  382. @course = Course.find(params[:course_id])
  383. elsif params[:org_subfield_id]
  384. @org_subfield = OrgSubfield.find(params[:org_subfield_id])
  385. end
  386. rescue ActiveRecord::RecordNotFound
  387. render_404
  388. end
  389. def find_contest_by_contest_id
  390. @contest = Contest.find(params[:contest_id])
  391. rescue ActiveRecord::RecordNotFound
  392. render_404
  393. end
  394. #���course_id��project
  395. def find_project_by_course_id
  396. @bid = Bid.find params[:course_id]
  397. @project = @bid.courses[0]
  398. rescue ActiveRecord::RecordNotFound
  399. render_404
  400. end
  401. # Find a project based on params[:project_id]
  402. # TODO: some subclasses override this, see about merging their logic
  403. def find_optional_project
  404. @project = Project.find(params[:project_id]) unless params[:project_id].blank?
  405. allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
  406. allowed ? true : deny_access
  407. rescue ActiveRecord::RecordNotFound
  408. render_404
  409. end
  410. def find_optional_contest
  411. @contest = Contest.find(params[:contest_id]) unless params[:contest_id].blank?
  412. allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @contest, :global => true)
  413. allowed ? true : deny_access
  414. rescue ActiveRecord::RecordNotFound
  415. render_404
  416. end
  417. # Finds and sets @project based on @object.project
  418. def find_project_from_association
  419. render_404 unless @object.present?
  420. @project = @object.project
  421. if @project == nil && @object.has_attribute?('course_id')
  422. @course = @object.course
  423. end
  424. end
  425. def find_contest_from_association
  426. render_404 unless @object.present?
  427. @contest =@object.contest
  428. end
  429. def find_model_object
  430. model = self.class.model_object
  431. if model
  432. @object = model.find(params[:id])
  433. self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  434. end
  435. rescue ActiveRecord::RecordNotFound
  436. render_404
  437. end
  438. #added by nwb
  439. #��ȡ�γ�
  440. def find_course
  441. @course= Course.find(params[:id])
  442. rescue ActiveRecord::RecordNotFound
  443. render_404
  444. end
  445. # def find_model_object_contest
  446. # model = self.class.model_object
  447. # if model
  448. # @object = model.find(params[:id])
  449. # self.instance_variable_set('@' + controller_name.singularize, @object) if @object
  450. # end
  451. # rescue ActiveRecord::RecordNotFound
  452. # render_404
  453. # end
  454. def self.
  455. model_object(model)
  456. self.model_object = model
  457. end
  458. # Find the issue whose id is the :id parameter
  459. # Raises a Unauthorized exception if the issue is not visible
  460. def find_issue
  461. # Issue.visible.find(...) can not be used to redirect user to the login form
  462. # if the issue actually exists but requires authentication
  463. @issue = Issue.find(params[:id])
  464. raise Unauthorized unless @issue.visible?
  465. @project = @issue.project
  466. rescue ActiveRecord::RecordNotFound
  467. render_404
  468. end
  469. # Find issues with a single :id param or :ids array param
  470. # Raises a Unauthorized exception if one of the issues is not visible
  471. def find_issues
  472. @issues = Issue.find_all_by_id(params[:id] || params[:ids])
  473. raise ActiveRecord::RecordNotFound if @issues.empty?
  474. raise Unauthorized unless @issues.all?(&:visible?)
  475. @projects = @issues.collect(&:project).compact.uniq
  476. @project = @projects.first if @projects.size == 1
  477. rescue ActiveRecord::RecordNotFound
  478. render_404
  479. end
  480. def find_attachments
  481. if (attachments = params[:attachments]).present?
  482. att = attachments.values.collect do |attachment|
  483. Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
  484. end
  485. att.compact!
  486. end
  487. @attachments = att || []
  488. end
  489. # make sure that the user is a member of the project (or admin) if project is private
  490. # used as a before_filter for actions that do not require any particular permission on the project
  491. def check_project_privacy
  492. if @project && !@project.archived?
  493. if @project.visible?
  494. true
  495. else
  496. deny_access
  497. end
  498. else
  499. @project = nil
  500. render_404
  501. false
  502. end
  503. end
  504. def back_url
  505. url = params[:back_url]
  506. if url.nil? && referer = request.env['HTTP_REFERER']
  507. url = CGI.unescape(referer.to_s)
  508. end
  509. url
  510. end
  511. def redirect_back_or_default(default, options={})
  512. back_url = '' #params[:back_url].to_s
  513. if back_url.present?
  514. begin
  515. uri = URI.parse(back_url)
  516. # do not redirect user to another host or to the login or register page
  517. if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
  518. back_url = back_url.gsub(%r{\/users\/(\d+)},"/users/"+default.id.to_s) if default.is_a?(:User)
  519. redirect_to(back_url)
  520. return
  521. end
  522. rescue URI::InvalidURIError
  523. logger.warn("Could not redirect to invalid URL #{back_url}")
  524. # redirect to default
  525. end
  526. elsif options[:referer]
  527. redirect_to_referer_or default
  528. return
  529. end
  530. redirect_to default
  531. false
  532. end
  533. # Redirects to the request referer if present, redirects to args or call block otherwise.
  534. def redirect_to_referer_or(*args, &block)
  535. redirect_to :back
  536. rescue ::ActionController::RedirectBackError
  537. if args.any?
  538. redirect_to *args
  539. elsif block_given?
  540. block.call
  541. else
  542. raise "#redirect_to_referer_or takes arguments or a block"
  543. end
  544. end
  545. def render_403(options={})
  546. @project = nil
  547. render_error({:message => :notice_not_authorized, :status => 403}.merge(options),'common/403')
  548. #render :template => 'common/403'
  549. return false
  550. end
  551. def render_404(options={})
  552. render_error({:message => :notice_file_not_found, :status => 404}.merge(options),'common/404')
  553. #render :template => 'common/404'
  554. return false
  555. end
  556. # Renders an error response
  557. def render_error(arg,template = 'common/error')
  558. arg = {:message => arg} unless arg.is_a?(Hash)
  559. @message = arg[:message]
  560. @lay = arg[:layout]
  561. @message = l(@message) if @message.is_a?(Symbol)
  562. @status = arg[:status] || 500
  563. respond_to do |format|
  564. format.html {
  565. if @lay
  566. render :template => template, :layout => @lay,:status => @status
  567. else
  568. render :template => template, :layout => use_layout, :status => @status
  569. end
  570. }
  571. format.any { head @status }
  572. end
  573. end
  574. # Handler for ActionView::MissingTemplate exception
  575. def missing_template
  576. logger.warn "Missing template, responding with 404"
  577. @project = nil
  578. render_404
  579. end
  580. # Filter for actions that provide an API response
  581. # but have no HTML representation for non admin users
  582. def require_admin_or_api_request
  583. return true if api_request?
  584. if User.current.admin?
  585. true
  586. elsif User.current.logged?
  587. render_error(:status => 406)
  588. else
  589. deny_access
  590. end
  591. end
  592. # Picks which layout to use based on the request
  593. #
  594. # @return [boolean, string] name of the layout to use or false for no layout
  595. def use_layout
  596. request.xhr? ? false : 'users_base'
  597. end
  598. def invalid_authenticity_token
  599. if api_request?
  600. logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
  601. end
  602. #render_error "Invalid form authenticity token."
  603. redirect_to signin_path(:login=>true)
  604. end
  605. def render_feed(items, options={})
  606. @items = items || []
  607. @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
  608. @items = @items.slice(0, Setting.feeds_limit.to_i)
  609. @title = options[:title] || Setting.app_title
  610. render :template => "common/feed", :formats => [:atom], :layout => false,
  611. :content_type => 'application/atom+xml'
  612. end
  613. def self.accept_rss_auth(*actions)
  614. if actions.any?
  615. self.accept_rss_auth_actions = actions
  616. else
  617. self.accept_rss_auth_actions || []
  618. end
  619. end
  620. def accept_rss_auth?(action=action_name)
  621. self.class.accept_rss_auth.include?(action.to_sym)
  622. end
  623. def self.accept_api_auth(*actions)
  624. if actions.any?
  625. self.accept_api_auth_actions = actions
  626. else
  627. self.accept_api_auth_actions || []
  628. end
  629. end
  630. def accept_api_auth?(action=action_name)
  631. self.class.accept_api_auth.include?(action.to_sym)
  632. end
  633. # Returns the number of objects that should be displayed
  634. # on the paginated list
  635. def per_page_option
  636. per_page = nil
  637. if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
  638. per_page = params[:per_page].to_s.to_i
  639. session[:per_page] = per_page
  640. elsif session[:per_page]
  641. per_page = session[:per_page]
  642. else
  643. per_page = Setting.per_page_options_array.first || 25
  644. end
  645. per_page
  646. end
  647. # Returns offset and limit used to retrieve objects
  648. # for an API response based on offset, limit and page parameters
  649. def api_offset_and_limit(options=params)
  650. if options[:offset].present?
  651. offset = options[:offset].to_i
  652. if offset < 0
  653. offset = 0
  654. end
  655. end
  656. limit = options[:limit].to_i
  657. if limit < 1
  658. limit = 25
  659. elsif limit > 100
  660. limit = 100
  661. end
  662. if offset.nil? && options[:page].present?
  663. offset = (options[:page].to_i - 1) * limit
  664. offset = 0 if offset < 0
  665. offset ||= 0
  666. end
  667. [offset, limit]
  668. end
  669. # qvalues http header parser
  670. # code taken from webrick
  671. def parse_qvalues(value)
  672. tmp = []
  673. if value
  674. parts = value.split(/,\s*/)
  675. parts.each {|part|
  676. if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
  677. val = m[1]
  678. q = (m[2] or 1).to_f
  679. tmp.push([val, q])
  680. end
  681. }
  682. tmp = tmp.sort_by{|val, q| -q}
  683. tmp.collect!{|val, q| val}
  684. end
  685. return tmp
  686. rescue
  687. nil
  688. end
  689. # Returns a string that can be used as filename value in Content-Disposition header
  690. def filename_for_content_disposition(name)
  691. request.env['HTTP_USER_AGENT'] =~ %r{MSIE|Trident} ? ERB::Util.url_encode(name) : name
  692. end
  693. def api_request?
  694. return false if params[:controller] == 'at'
  695. %w(xml json).include? params[:format]
  696. end
  697. # Returns the API key present in the request
  698. def api_key_from_request
  699. if params[:key].present?
  700. params[:key].to_s
  701. elsif request.headers["X-Redmine-API-Key"].present?
  702. request.headers["X-Redmine-API-Key"].to_s
  703. end
  704. end
  705. # Returns the API 'switch user' value if present
  706. def api_switch_user_from_request
  707. request.headers["X-Redmine-Switch-User"].to_s.presence
  708. end
  709. # Renders a warning flash if obj has unsaved attachments
  710. def render_attachment_warning_if_needed(obj)
  711. flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
  712. end
  713. # Sets the `flash` notice or error based the number of issues that did not save
  714. #
  715. # @param [Array, Issue] issues all of the saved and unsaved Issues
  716. # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
  717. def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
  718. if unsaved_issue_ids.empty?
  719. flash[:notice] = l(:notice_successful_update) unless issues.empty?
  720. else
  721. flash[:error] = l(:notice_failed_to_save_issues,
  722. :count => unsaved_issue_ids.size,
  723. :total => issues.size,
  724. :ids => '#' + unsaved_issue_ids.join(', #'))
  725. end
  726. end
  727. # Rescues an invalid query statement. Just in case...
  728. def query_statement_invalid(exception)
  729. logger.error "Query::StatementInvalid: #{exception.message}" if logger
  730. session.delete(:query)
  731. sort_clear if respond_to?(:sort_clear)
  732. render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
  733. end
  734. # Renders a 200 response for successfull updates or deletions via the API
  735. def render_api_ok
  736. render_api_head :ok
  737. end
  738. # Renders a head API response
  739. def render_api_head(status)
  740. # #head would return a response body with one space
  741. render :text => '', :status => status, :layout => nil
  742. end
  743. # Renders API response on validation failure
  744. def render_validation_errors(objects)
  745. if objects.is_a?(Array)
  746. @error_messages = objects.map {|object| object.errors.full_messages}.flatten
  747. else
  748. @error_messages = objects.errors.full_messages
  749. end
  750. render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
  751. end
  752. # Overrides #_include_layout? so that #render with no arguments
  753. # doesn't use the layout for api requests
  754. def _include_layout?(*args)
  755. api_request? ? false : super
  756. end
  757. ## Please added code in html.
  758. # <div class="pagination"><%= pagination_links_full @obj_pages, @obj_count, :per_page_links => false %></div>
  759. def paginateHelper obj, pre_size=20
  760. @obj_count = obj.count
  761. @obj_pages = Paginator.new @obj_count, pre_size, params['page']
  762. if obj.kind_of? ActiveRecord::Base or obj.kind_of? ActiveRecord::Relation
  763. obj.limit(@obj_pages.per_page).offset(@obj_pages.offset)
  764. elsif obj.kind_of? Array
  765. obj[@obj_pages.offset, @obj_pages.per_page]
  766. else
  767. logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
  768. raise RuntimeError, 'unknow type, Please input you type into this helper.'
  769. end
  770. end
  771. def paginateHelper_for_members obj, pre_size=10
  772. @obj_count = StudentsForCourse.find_by_sql("select count(id) as mem_count from students_for_courses where course_id = #{@course.id}")[0][:mem_count].to_s.to_i
  773. @obj_pages = Paginator.new @obj_count, pre_size, params['page']
  774. if obj.kind_of? ActiveRecord::Base or obj.kind_of? ActiveRecord::Relation
  775. obj.limit(@obj_pages.per_page).offset(0)
  776. elsif obj.kind_of? Array
  777. obj[0, @obj_pages.per_page]
  778. else
  779. logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
  780. raise RuntimeError, 'unknow type, Please input you type into this helper.'
  781. end
  782. end
  783. #查找首页相关信息
  784. def find_first_page
  785. @first_page = FirstPage.find_by_page_type('project')
  786. if @first_page.nil?
  787. @first_page = FirstPage.new
  788. @first_page.page_type = 'project'
  789. @first_page.description = ""
  790. @first_page.save()
  791. end
  792. @show_course = @first_page.show_course
  793. @show_contest = @first_page.show_contest
  794. end
  795. def find_web_footer
  796. @organizer = WebFooterOranizer.first
  797. @companies = WebFooterCompany.all
  798. end
  799. def password_authentication
  800. user, last_login_on = User.try_to_login(params[:user_name], params[:password])
  801. successful_authentication(user, last_login_on)
  802. end
  803. def successful_authentication(user, last_login_on)
  804. logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
  805. # Valid user
  806. self.logged_user = user
  807. # generate a key and set cookie if autologin
  808. if params[:autologin] && Setting.autologin?
  809. set_autologin_cookie(user)
  810. end
  811. call_hook(:controller_account_success_authentication_after, {:user => user })
  812. end
  813. def user_unlogged_check
  814. if !User.current.logged?
  815. render(:partial => 'organizations/unlogged_tip')
  816. return false
  817. end
  818. true
  819. end
  820. end

软件技术创新是当今国家整体创新能力的重要基础和发展引擎。近年来,大众参与的软件创新与创业活动已经成为网络时代软件开发和应用的新形态,正在快速改变着全球软件创新模式和软件产业格局。 ...