##// END OF EJS Templates
Refactor: pull #query_statement_invalid up to ApplicationController....
Eric Davis -
r3582:488879d9cf63
parent child
Show More
@@ -1,332 +1,341
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'uri'
19 19 require 'cgi'
20 20
21 21 class ApplicationController < ActionController::Base
22 22 include Redmine::I18n
23 23
24 24 layout 'base'
25 25 exempt_from_layout 'builder'
26 26
27 27 # Remove broken cookie after upgrade from 0.8.x (#4292)
28 28 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
29 29 # TODO: remove it when Rails is fixed
30 30 before_filter :delete_broken_cookies
31 31 def delete_broken_cookies
32 32 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
33 33 cookies.delete '_redmine_session'
34 34 redirect_to home_path
35 35 return false
36 36 end
37 37 end
38 38
39 39 before_filter :user_setup, :check_if_login_required, :set_localization
40 40 filter_parameter_logging :password
41 41 protect_from_forgery
42 42
43 43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
44 44
45 45 include Redmine::Search::Controller
46 46 include Redmine::MenuManager::MenuController
47 47 helper Redmine::MenuManager::MenuHelper
48 48
49 49 Redmine::Scm::Base.all.each do |scm|
50 50 require_dependency "repository/#{scm.underscore}"
51 51 end
52 52
53 53 def user_setup
54 54 # Check the settings cache for each request
55 55 Setting.check_cache
56 56 # Find the current user
57 57 User.current = find_current_user
58 58 end
59 59
60 60 # Returns the current user or nil if no user is logged in
61 61 # and starts a session if needed
62 62 def find_current_user
63 63 if session[:user_id]
64 64 # existing session
65 65 (User.active.find(session[:user_id]) rescue nil)
66 66 elsif cookies[:autologin] && Setting.autologin?
67 67 # auto-login feature starts a new session
68 68 user = User.try_to_autologin(cookies[:autologin])
69 69 session[:user_id] = user.id if user
70 70 user
71 71 elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
72 72 # RSS key authentication does not start a session
73 73 User.find_by_rss_key(params[:key])
74 74 elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format])
75 75 if params[:key].present? && accept_key_auth_actions.include?(params[:action])
76 76 # Use API key
77 77 User.find_by_api_key(params[:key])
78 78 else
79 79 # HTTP Basic, either username/password or API key/random
80 80 authenticate_with_http_basic do |username, password|
81 81 User.try_to_login(username, password) || User.find_by_api_key(username)
82 82 end
83 83 end
84 84 end
85 85 end
86 86
87 87 # Sets the logged in user
88 88 def logged_user=(user)
89 89 reset_session
90 90 if user && user.is_a?(User)
91 91 User.current = user
92 92 session[:user_id] = user.id
93 93 else
94 94 User.current = User.anonymous
95 95 end
96 96 end
97 97
98 98 # check if login is globally required to access the application
99 99 def check_if_login_required
100 100 # no check needed if user is already logged in
101 101 return true if User.current.logged?
102 102 require_login if Setting.login_required?
103 103 end
104 104
105 105 def set_localization
106 106 lang = nil
107 107 if User.current.logged?
108 108 lang = find_language(User.current.language)
109 109 end
110 110 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
111 111 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first.downcase
112 112 if !accept_lang.blank?
113 113 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
114 114 end
115 115 end
116 116 lang ||= Setting.default_language
117 117 set_language_if_valid(lang)
118 118 end
119 119
120 120 def require_login
121 121 if !User.current.logged?
122 122 # Extract only the basic url parameters on non-GET requests
123 123 if request.get?
124 124 url = url_for(params)
125 125 else
126 126 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
127 127 end
128 128 respond_to do |format|
129 129 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
130 130 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
131 131 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
132 132 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
133 133 end
134 134 return false
135 135 end
136 136 true
137 137 end
138 138
139 139 def require_admin
140 140 return unless require_login
141 141 if !User.current.admin?
142 142 render_403
143 143 return false
144 144 end
145 145 true
146 146 end
147 147
148 148 def deny_access
149 149 User.current.logged? ? render_403 : require_login
150 150 end
151 151
152 152 # Authorize the user for the requested action
153 153 def authorize(ctrl = params[:controller], action = params[:action], global = false)
154 154 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
155 155 allowed ? true : deny_access
156 156 end
157 157
158 158 # Authorize the user for the requested action outside a project
159 159 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
160 160 authorize(ctrl, action, global)
161 161 end
162 162
163 163 # Find project of id params[:id]
164 164 def find_project
165 165 @project = Project.find(params[:id])
166 166 rescue ActiveRecord::RecordNotFound
167 167 render_404
168 168 end
169 169
170 170 # Finds and sets @project based on @object.project
171 171 def find_project_from_association
172 172 render_404 unless @object.present?
173 173
174 174 @project = @object.project
175 175 rescue ActiveRecord::RecordNotFound
176 176 render_404
177 177 end
178 178
179 179 def find_model_object
180 180 model = self.class.read_inheritable_attribute('model_object')
181 181 if model
182 182 @object = model.find(params[:id])
183 183 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
184 184 end
185 185 rescue ActiveRecord::RecordNotFound
186 186 render_404
187 187 end
188 188
189 189 def self.model_object(model)
190 190 write_inheritable_attribute('model_object', model)
191 191 end
192 192
193 193 # make sure that the user is a member of the project (or admin) if project is private
194 194 # used as a before_filter for actions that do not require any particular permission on the project
195 195 def check_project_privacy
196 196 if @project && @project.active?
197 197 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
198 198 true
199 199 else
200 200 User.current.logged? ? render_403 : require_login
201 201 end
202 202 else
203 203 @project = nil
204 204 render_404
205 205 false
206 206 end
207 207 end
208 208
209 209 def redirect_back_or_default(default)
210 210 back_url = CGI.unescape(params[:back_url].to_s)
211 211 if !back_url.blank?
212 212 begin
213 213 uri = URI.parse(back_url)
214 214 # do not redirect user to another host or to the login or register page
215 215 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
216 216 redirect_to(back_url)
217 217 return
218 218 end
219 219 rescue URI::InvalidURIError
220 220 # redirect to default
221 221 end
222 222 end
223 223 redirect_to default
224 224 end
225 225
226 226 def render_403
227 227 @project = nil
228 228 respond_to do |format|
229 229 format.html { render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403 }
230 230 format.atom { head 403 }
231 231 format.xml { head 403 }
232 232 format.json { head 403 }
233 233 end
234 234 return false
235 235 end
236 236
237 237 def render_404
238 238 respond_to do |format|
239 239 format.html { render :template => "common/404", :layout => !request.xhr?, :status => 404 }
240 240 format.atom { head 404 }
241 241 format.xml { head 404 }
242 242 format.json { head 404 }
243 243 end
244 244 return false
245 245 end
246 246
247 247 def render_error(msg)
248 248 respond_to do |format|
249 249 format.html {
250 250 flash.now[:error] = msg
251 251 render :text => '', :layout => !request.xhr?, :status => 500
252 252 }
253 253 format.atom { head 500 }
254 254 format.xml { head 500 }
255 255 format.json { head 500 }
256 256 end
257 257 end
258 258
259 259 def invalid_authenticity_token
260 260 if api_request?
261 261 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
262 262 end
263 263 render_error "Invalid form authenticity token."
264 264 end
265 265
266 266 def render_feed(items, options={})
267 267 @items = items || []
268 268 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
269 269 @items = @items.slice(0, Setting.feeds_limit.to_i)
270 270 @title = options[:title] || Setting.app_title
271 271 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
272 272 end
273 273
274 274 def self.accept_key_auth(*actions)
275 275 actions = actions.flatten.map(&:to_s)
276 276 write_inheritable_attribute('accept_key_auth_actions', actions)
277 277 end
278 278
279 279 def accept_key_auth_actions
280 280 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
281 281 end
282 282
283 283 # Returns the number of objects that should be displayed
284 284 # on the paginated list
285 285 def per_page_option
286 286 per_page = nil
287 287 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
288 288 per_page = params[:per_page].to_s.to_i
289 289 session[:per_page] = per_page
290 290 elsif session[:per_page]
291 291 per_page = session[:per_page]
292 292 else
293 293 per_page = Setting.per_page_options_array.first || 25
294 294 end
295 295 per_page
296 296 end
297 297
298 298 # qvalues http header parser
299 299 # code taken from webrick
300 300 def parse_qvalues(value)
301 301 tmp = []
302 302 if value
303 303 parts = value.split(/,\s*/)
304 304 parts.each {|part|
305 305 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
306 306 val = m[1]
307 307 q = (m[2] or 1).to_f
308 308 tmp.push([val, q])
309 309 end
310 310 }
311 311 tmp = tmp.sort_by{|val, q| -q}
312 312 tmp.collect!{|val, q| val}
313 313 end
314 314 return tmp
315 315 rescue
316 316 nil
317 317 end
318 318
319 319 # Returns a string that can be used as filename value in Content-Disposition header
320 320 def filename_for_content_disposition(name)
321 321 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
322 322 end
323 323
324 324 def api_request?
325 325 %w(xml json).include? params[:format]
326 326 end
327 327
328 328 # Renders a warning flash if obj has unsaved attachments
329 329 def render_attachment_warning_if_needed(obj)
330 330 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
331 331 end
332
333 # Rescues an invalid query statement. Just in case...
334 def query_statement_invalid(exception)
335 logger.error "Query::StatementInvalid: #{exception.message}" if logger
336 session.delete(:query)
337 sort_clear if respond_to?(:sort_clear)
338 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
339 end
340
332 341 end
@@ -1,63 +1,56
1 1 class GanttsController < ApplicationController
2 2 before_filter :find_optional_project
3 3
4 4 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
5 5
6 6 helper :issues
7 7 helper :projects
8 8 helper :queries
9 9 include QueriesHelper
10 helper :sort
11 include SortHelper
10 12 include Redmine::Export::PDF
11 13
12 14 def show
13 15 @gantt = Redmine::Helpers::Gantt.new(params)
14 16 retrieve_query
15 17 @query.group_by = nil
16 18 if @query.valid?
17 19 events = []
18 20 # Issues that have start and due dates
19 21 events += @query.issues(:include => [:tracker, :assigned_to, :priority],
20 22 :order => "start_date, due_date",
21 23 :conditions => ["(((start_date>=? and start_date<=?) or (due_date>=? and due_date<=?) or (start_date<? and due_date>?)) and start_date is not null and due_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
22 24 )
23 25 # Issues that don't have a due date but that are assigned to a version with a date
24 26 events += @query.issues(:include => [:tracker, :assigned_to, :priority, :fixed_version],
25 27 :order => "start_date, effective_date",
26 28 :conditions => ["(((start_date>=? and start_date<=?) or (effective_date>=? and effective_date<=?) or (start_date<? and effective_date>?)) and start_date is not null and due_date is null and effective_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
27 29 )
28 30 # Versions
29 31 events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @gantt.date_from, @gantt.date_to])
30 32
31 33 @gantt.events = events
32 34 end
33 35
34 36 basename = (@project ? "#{@project.identifier}-" : '') + 'gantt'
35 37
36 38 respond_to do |format|
37 39 format.html { render :action => "show", :layout => !request.xhr? }
38 40 format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @gantt.respond_to?('to_image')
39 41 format.pdf { send_data(gantt_to_pdf(@gantt, @project), :type => 'application/pdf', :filename => "#{basename}.pdf") }
40 42 end
41 43 end
42 44
43 45 private
44 46
45 # Rescues an invalid query statement. Just in case...
46 # TODO: Refactor, move to ApplicationController with IssuesController
47 def query_statement_invalid(exception)
48 logger.error "Query::StatementInvalid: #{exception.message}" if logger
49 session.delete(:query)
50 sort_clear
51 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
52 end
53
54 47 # TODO: Refactor, duplicates IssuesController
55 48 def find_optional_project
56 49 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
57 50 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
58 51 allowed ? true : deny_access
59 52 rescue ActiveRecord::RecordNotFound
60 53 render_404
61 54 end
62 55
63 56 end
@@ -1,523 +1,515
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2008 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class IssuesController < ApplicationController
19 19 menu_item :new_issue, :only => :new
20 20 default_search_scope :issues
21 21
22 22 before_filter :find_issue, :only => [:show, :edit, :update, :reply]
23 23 before_filter :find_issues, :only => [:bulk_edit, :move, :destroy]
24 24 before_filter :find_project, :only => [:new, :create, :update_form, :preview, :auto_complete]
25 25 before_filter :authorize, :except => [:index, :changes, :calendar, :preview, :context_menu]
26 26 before_filter :find_optional_project, :only => [:index, :changes, :calendar]
27 27 before_filter :check_for_default_issue_status, :only => [:new, :create]
28 28 before_filter :build_new_issue_from_params, :only => [:new, :create]
29 29 accept_key_auth :index, :show, :changes
30 30
31 31 rescue_from Query::StatementInvalid, :with => :query_statement_invalid
32 32
33 33 helper :journals
34 34 helper :projects
35 35 include ProjectsHelper
36 36 helper :custom_fields
37 37 include CustomFieldsHelper
38 38 helper :issue_relations
39 39 include IssueRelationsHelper
40 40 helper :watchers
41 41 include WatchersHelper
42 42 helper :attachments
43 43 include AttachmentsHelper
44 44 helper :queries
45 45 include QueriesHelper
46 46 helper :sort
47 47 include SortHelper
48 48 include IssuesHelper
49 49 helper :timelog
50 50 include Redmine::Export::PDF
51 51
52 52 verify :method => [:post, :delete],
53 53 :only => :destroy,
54 54 :render => { :nothing => true, :status => :method_not_allowed }
55 55
56 56 verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
57 57 verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
58 58
59 59 def index
60 60 retrieve_query
61 61 sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
62 62 sort_update(@query.sortable_columns)
63 63
64 64 if @query.valid?
65 65 limit = case params[:format]
66 66 when 'csv', 'pdf'
67 67 Setting.issues_export_limit.to_i
68 68 when 'atom'
69 69 Setting.feeds_limit.to_i
70 70 else
71 71 per_page_option
72 72 end
73 73
74 74 @issue_count = @query.issue_count
75 75 @issue_pages = Paginator.new self, @issue_count, limit, params['page']
76 76 @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
77 77 :order => sort_clause,
78 78 :offset => @issue_pages.current.offset,
79 79 :limit => limit)
80 80 @issue_count_by_group = @query.issue_count_by_group
81 81
82 82 respond_to do |format|
83 83 format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
84 84 format.xml { render :layout => false }
85 85 format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
86 86 format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
87 87 format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
88 88 end
89 89 else
90 90 # Send html if the query is not valid
91 91 render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
92 92 end
93 93 rescue ActiveRecord::RecordNotFound
94 94 render_404
95 95 end
96 96
97 97 def changes
98 98 retrieve_query
99 99 sort_init 'id', 'desc'
100 100 sort_update(@query.sortable_columns)
101 101
102 102 if @query.valid?
103 103 @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
104 104 :limit => 25)
105 105 end
106 106 @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
107 107 render :layout => false, :content_type => 'application/atom+xml'
108 108 rescue ActiveRecord::RecordNotFound
109 109 render_404
110 110 end
111 111
112 112 def show
113 113 @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
114 114 @journals.each_with_index {|j,i| j.indice = i+1}
115 115 @journals.reverse! if User.current.wants_comments_in_reverse_order?
116 116 @changesets = @issue.changesets.visible.all
117 117 @changesets.reverse! if User.current.wants_comments_in_reverse_order?
118 118 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
119 119 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
120 120 @priorities = IssuePriority.all
121 121 @time_entry = TimeEntry.new
122 122 respond_to do |format|
123 123 format.html { render :template => 'issues/show.rhtml' }
124 124 format.xml { render :layout => false }
125 125 format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
126 126 format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
127 127 end
128 128 end
129 129
130 130 # Add a new issue
131 131 # The new issue will be created from an existing one if copy_from parameter is given
132 132 def new
133 133 render :action => 'new', :layout => !request.xhr?
134 134 end
135 135
136 136 def create
137 137 call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
138 138 if @issue.save
139 139 attachments = Attachment.attach_files(@issue, params[:attachments])
140 140 render_attachment_warning_if_needed(@issue)
141 141 flash[:notice] = l(:notice_successful_create)
142 142 call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
143 143 respond_to do |format|
144 144 format.html {
145 145 redirect_to(params[:continue] ? { :action => 'new', :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
146 146 { :action => 'show', :id => @issue })
147 147 }
148 148 format.xml { render :action => 'show', :status => :created, :location => url_for(:controller => 'issues', :action => 'show', :id => @issue) }
149 149 end
150 150 return
151 151 else
152 152 respond_to do |format|
153 153 format.html { render :action => 'new' }
154 154 format.xml { render(:xml => @issue.errors, :status => :unprocessable_entity); return }
155 155 end
156 156 end
157 157 end
158 158
159 159 # Attributes that can be updated on workflow transition (without :edit permission)
160 160 # TODO: make it configurable (at least per role)
161 161 UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
162 162
163 163 def edit
164 164 update_issue_from_params
165 165
166 166 @journal = @issue.current_journal
167 167
168 168 respond_to do |format|
169 169 format.html { }
170 170 format.xml { }
171 171 end
172 172 end
173 173
174 174 def update
175 175 update_issue_from_params
176 176
177 177 if @issue.save_issue_with_child_records(params, @time_entry)
178 178 render_attachment_warning_if_needed(@issue)
179 179 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
180 180
181 181 respond_to do |format|
182 182 format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
183 183 format.xml { head :ok }
184 184 end
185 185 else
186 186 render_attachment_warning_if_needed(@issue)
187 187 flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
188 188 @journal = @issue.current_journal
189 189
190 190 respond_to do |format|
191 191 format.html { render :action => 'edit' }
192 192 format.xml { render :xml => @issue.errors, :status => :unprocessable_entity }
193 193 end
194 194 end
195 195 end
196 196
197 197 def reply
198 198 journal = Journal.find(params[:journal_id]) if params[:journal_id]
199 199 if journal
200 200 user = journal.user
201 201 text = journal.notes
202 202 else
203 203 user = @issue.author
204 204 text = @issue.description
205 205 end
206 206 # Replaces pre blocks with [...]
207 207 text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
208 208 content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
209 209 content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
210 210
211 211 render(:update) { |page|
212 212 page.<< "$('notes').value = \"#{escape_javascript content}\";"
213 213 page.show 'update'
214 214 page << "Form.Element.focus('notes');"
215 215 page << "Element.scrollTo('update');"
216 216 page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
217 217 }
218 218 end
219 219
220 220 # Bulk edit a set of issues
221 221 def bulk_edit
222 222 @issues.sort!
223 223 if request.post?
224 224 attributes = (params[:issue] || {}).reject {|k,v| v.blank?}
225 225 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
226 226 attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
227 227
228 228 unsaved_issue_ids = []
229 229 @issues.each do |issue|
230 230 issue.reload
231 231 journal = issue.init_journal(User.current, params[:notes])
232 232 issue.safe_attributes = attributes
233 233 call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
234 234 unless issue.save
235 235 # Keep unsaved issue ids to display them in flash error
236 236 unsaved_issue_ids << issue.id
237 237 end
238 238 end
239 239 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
240 240 redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
241 241 return
242 242 end
243 243 @available_statuses = Workflow.available_statuses(@project)
244 244 @custom_fields = @project.all_issue_custom_fields
245 245 end
246 246
247 247 def move
248 248 @issues.sort!
249 249 @copy = params[:copy_options] && params[:copy_options][:copy]
250 250 @allowed_projects = Issue.allowed_target_projects_on_move
251 251 @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
252 252 @target_project ||= @project
253 253 @trackers = @target_project.trackers
254 254 @available_statuses = Workflow.available_statuses(@project)
255 255 if request.post?
256 256 new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
257 257 unsaved_issue_ids = []
258 258 moved_issues = []
259 259 @issues.each do |issue|
260 260 issue.reload
261 261 changed_attributes = {}
262 262 [:assigned_to_id, :status_id, :start_date, :due_date].each do |valid_attribute|
263 263 unless params[valid_attribute].blank?
264 264 changed_attributes[valid_attribute] = (params[valid_attribute] == 'none' ? nil : params[valid_attribute])
265 265 end
266 266 end
267 267 issue.init_journal(User.current)
268 268 call_hook(:controller_issues_move_before_save, { :params => params, :issue => issue, :target_project => @target_project, :copy => !!@copy })
269 269 if r = issue.move_to_project(@target_project, new_tracker, {:copy => @copy, :attributes => changed_attributes})
270 270 moved_issues << r
271 271 else
272 272 unsaved_issue_ids << issue.id
273 273 end
274 274 end
275 275 set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
276 276
277 277 if params[:follow]
278 278 if @issues.size == 1 && moved_issues.size == 1
279 279 redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
280 280 else
281 281 redirect_to :controller => 'issues', :action => 'index', :project_id => (@target_project || @project)
282 282 end
283 283 else
284 284 redirect_to :controller => 'issues', :action => 'index', :project_id => @project
285 285 end
286 286 return
287 287 end
288 288 render :layout => false if request.xhr?
289 289 end
290 290
291 291 def destroy
292 292 @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
293 293 if @hours > 0
294 294 case params[:todo]
295 295 when 'destroy'
296 296 # nothing to do
297 297 when 'nullify'
298 298 TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
299 299 when 'reassign'
300 300 reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
301 301 if reassign_to.nil?
302 302 flash.now[:error] = l(:error_issue_not_found_in_project)
303 303 return
304 304 else
305 305 TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
306 306 end
307 307 else
308 308 unless params[:format] == 'xml'
309 309 # display the destroy form if it's a user request
310 310 return
311 311 end
312 312 end
313 313 end
314 314 @issues.each(&:destroy)
315 315 respond_to do |format|
316 316 format.html { redirect_to :action => 'index', :project_id => @project }
317 317 format.xml { head :ok }
318 318 end
319 319 end
320 320
321 321 def calendar
322 322 if params[:year] and params[:year].to_i > 1900
323 323 @year = params[:year].to_i
324 324 if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
325 325 @month = params[:month].to_i
326 326 end
327 327 end
328 328 @year ||= Date.today.year
329 329 @month ||= Date.today.month
330 330
331 331 @calendar = Redmine::Helpers::Calendar.new(Date.civil(@year, @month, 1), current_language, :month)
332 332 retrieve_query
333 333 @query.group_by = nil
334 334 if @query.valid?
335 335 events = []
336 336 events += @query.issues(:include => [:tracker, :assigned_to, :priority],
337 337 :conditions => ["((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt]
338 338 )
339 339 events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @calendar.startdt, @calendar.enddt])
340 340
341 341 @calendar.events = events
342 342 end
343 343
344 344 render :layout => false if request.xhr?
345 345 end
346 346
347 347 def context_menu
348 348 @issues = Issue.find_all_by_id(params[:ids], :include => :project)
349 349 if (@issues.size == 1)
350 350 @issue = @issues.first
351 351 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
352 352 end
353 353 projects = @issues.collect(&:project).compact.uniq
354 354 @project = projects.first if projects.size == 1
355 355
356 356 @can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
357 357 :log_time => (@project && User.current.allowed_to?(:log_time, @project)),
358 358 :update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
359 359 :move => (@project && User.current.allowed_to?(:move_issues, @project)),
360 360 :copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
361 361 :delete => (@project && User.current.allowed_to?(:delete_issues, @project))
362 362 }
363 363 if @project
364 364 @assignables = @project.assignable_users
365 365 @assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
366 366 @trackers = @project.trackers
367 367 end
368 368
369 369 @priorities = IssuePriority.all.reverse
370 370 @statuses = IssueStatus.find(:all, :order => 'position')
371 371 @back = params[:back_url] || request.env['HTTP_REFERER']
372 372
373 373 render :layout => false
374 374 end
375 375
376 376 def update_form
377 377 if params[:id].blank?
378 378 @issue = Issue.new
379 379 @issue.project = @project
380 380 else
381 381 @issue = @project.issues.visible.find(params[:id])
382 382 end
383 383 @issue.attributes = params[:issue]
384 384 @allowed_statuses = ([@issue.status] + @issue.status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
385 385 @priorities = IssuePriority.all
386 386
387 387 render :partial => 'attributes'
388 388 end
389 389
390 390 def preview
391 391 @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
392 392 if @issue
393 393 @attachements = @issue.attachments
394 394 @description = params[:issue] && params[:issue][:description]
395 395 if @description && @description.gsub(/(\r?\n|\n\r?)/, "\n") == @issue.description.to_s.gsub(/(\r?\n|\n\r?)/, "\n")
396 396 @description = nil
397 397 end
398 398 @notes = params[:notes]
399 399 else
400 400 @description = (params[:issue] ? params[:issue][:description] : nil)
401 401 end
402 402 render :layout => false
403 403 end
404 404
405 405 def auto_complete
406 406 @issues = []
407 407 q = params[:q].to_s
408 408 if q.match(/^\d+$/)
409 409 @issues << @project.issues.visible.find_by_id(q.to_i)
410 410 end
411 411 unless q.blank?
412 412 @issues += @project.issues.visible.find(:all, :conditions => ["LOWER(#{Issue.table_name}.subject) LIKE ?", "%#{q.downcase}%"], :limit => 10)
413 413 end
414 414 render :layout => false
415 415 end
416 416
417 417 private
418 418 def find_issue
419 419 @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
420 420 @project = @issue.project
421 421 rescue ActiveRecord::RecordNotFound
422 422 render_404
423 423 end
424 424
425 425 # Filter for bulk operations
426 426 def find_issues
427 427 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
428 428 raise ActiveRecord::RecordNotFound if @issues.empty?
429 429 projects = @issues.collect(&:project).compact.uniq
430 430 if projects.size == 1
431 431 @project = projects.first
432 432 else
433 433 # TODO: let users bulk edit/move/destroy issues from different projects
434 434 render_error 'Can not bulk edit/move/destroy issues from different projects'
435 435 return false
436 436 end
437 437 rescue ActiveRecord::RecordNotFound
438 438 render_404
439 439 end
440 440
441 441 def find_project
442 442 project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
443 443 @project = Project.find(project_id)
444 444 rescue ActiveRecord::RecordNotFound
445 445 render_404
446 446 end
447 447
448 448 def find_optional_project
449 449 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
450 450 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
451 451 allowed ? true : deny_access
452 452 rescue ActiveRecord::RecordNotFound
453 453 render_404
454 454 end
455 455
456 # Rescues an invalid query statement. Just in case...
457 def query_statement_invalid(exception)
458 logger.error "Query::StatementInvalid: #{exception.message}" if logger
459 session.delete(:query)
460 sort_clear
461 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
462 end
463
464 456 # Used by #edit and #update to set some common instance variables
465 457 # from the params
466 458 # TODO: Refactor, not everything in here is needed by #edit
467 459 def update_issue_from_params
468 460 @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
469 461 @priorities = IssuePriority.all
470 462 @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
471 463 @time_entry = TimeEntry.new
472 464
473 465 @notes = params[:notes]
474 466 @issue.init_journal(User.current, @notes)
475 467 # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
476 468 if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
477 469 attrs = params[:issue].dup
478 470 attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
479 471 attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
480 472 @issue.safe_attributes = attrs
481 473 end
482 474
483 475 end
484 476
485 477 # TODO: Refactor, lots of extra code in here
486 478 def build_new_issue_from_params
487 479 @issue = Issue.new
488 480 @issue.copy_from(params[:copy_from]) if params[:copy_from]
489 481 @issue.project = @project
490 482 # Tracker must be set before custom field values
491 483 @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
492 484 if @issue.tracker.nil?
493 485 render_error l(:error_no_tracker_in_project)
494 486 return false
495 487 end
496 488 if params[:issue].is_a?(Hash)
497 489 @issue.safe_attributes = params[:issue]
498 490 @issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
499 491 end
500 492 @issue.author = User.current
501 493 @issue.start_date ||= Date.today
502 494 @priorities = IssuePriority.all
503 495 @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
504 496 end
505 497
506 498 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
507 499 if unsaved_issue_ids.empty?
508 500 flash[:notice] = l(:notice_successful_update) unless issues.empty?
509 501 else
510 502 flash[:error] = l(:notice_failed_to_save_issues,
511 503 :count => unsaved_issue_ids.size,
512 504 :total => issues.size,
513 505 :ids => '#' + unsaved_issue_ids.join(', #'))
514 506 end
515 507 end
516 508
517 509 def check_for_default_issue_status
518 510 if IssueStatus.default.nil?
519 511 render_error l(:error_no_default_issue_status)
520 512 return false
521 513 end
522 514 end
523 515 end
General Comments 0
You need to be logged in to leave comments. Login now