]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
Merge branch 'pull/1765'
[rails.git] / app / controllers / trace_controller.rb
1 class TraceController < ApplicationController
2   layout "site", :except => :georss
3
4   skip_before_action :verify_authenticity_token, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
5   before_action :authorize_web
6   before_action :set_locale
7   before_action :require_user, :only => [:mine, :create, :edit, :delete]
8   before_action :authorize, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
9   before_action :check_database_readable, :except => [:api_read, :api_data]
10   before_action :check_database_writable, :only => [:create, :edit, :delete, :api_create, :api_update, :api_delete]
11   before_action :check_api_readable, :only => [:api_read, :api_data]
12   before_action :check_api_writable, :only => [:api_create, :api_update, :api_delete]
13   before_action :require_allow_read_gpx, :only => [:api_read, :api_data]
14   before_action :require_allow_write_gpx, :only => [:api_create, :api_update, :api_delete]
15   before_action :offline_warning, :only => [:mine, :view]
16   before_action :offline_redirect, :only => [:create, :edit, :delete, :data, :api_create, :api_delete, :api_data]
17   around_action :api_call_handle_error, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
18
19   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
20   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
21   def list
22     # from display name, pick up user id if one user's traces only
23     display_name = params[:display_name]
24     if display_name.present?
25       target_user = User.active.where(:display_name => display_name).first
26       if target_user.nil?
27         render_unknown_user display_name
28         return
29       end
30     end
31
32     # set title
33     @title = if target_user.nil?
34                t "trace.list.public_traces"
35              elsif current_user && current_user == target_user
36                t "trace.list.your_traces"
37              else
38                t "trace.list.public_traces_from", :user => target_user.display_name
39              end
40
41     @title += t "trace.list.tagged_with", :tags => params[:tag] if params[:tag]
42
43     # four main cases:
44     # 1 - all traces, logged in = all public traces + all user's (i.e + all mine)
45     # 2 - all traces, not logged in = all public traces
46     # 3 - user's traces, logged in as same user = all user's traces
47     # 4 - user's traces, not logged in as that user = all user's public traces
48     @traces = if target_user.nil? # all traces
49                 if current_user
50                   Trace.visible_to(current_user) # 1
51                 else
52                   Trace.visible_to_all # 2
53                 end
54               elsif current_user && current_user == target_user
55                 current_user.traces # 3 (check vs user id, so no join + can't pick up non-public traces by changing name)
56               else
57                 target_user.traces.visible_to_all # 4
58               end
59
60     @traces = @traces.tagged(params[:tag]) if params[:tag]
61
62     @params = params.permit(:display_name, :tag)
63
64     @page = (params[:page] || 1).to_i
65     @page_size = 20
66
67     @traces = @traces.visible
68     @traces = @traces.order(:id => :desc)
69     @traces = @traces.offset((@page - 1) * @page_size)
70     @traces = @traces.limit(@page_size)
71     @traces = @traces.includes(:user, :tags)
72
73     # put together SET of tags across traces, for related links
74     tagset = {}
75     @traces.each do |trace|
76       trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
77       trace.tags.each do |tag|
78         tagset[tag.tag] = tag.tag
79       end
80     end
81
82     # final helper vars for view
83     @target_user = target_user
84     @display_name = target_user.display_name if target_user
85     @all_tags = tagset.values
86   end
87
88   def mine
89     redirect_to :action => :list, :display_name => current_user.display_name
90   end
91
92   def view
93     @trace = Trace.find(params[:id])
94
95     if @trace && @trace.visible? &&
96        (@trace.public? || @trace.user == current_user)
97       @title = t "trace.view.title", :name => @trace.name
98     else
99       flash[:error] = t "trace.view.trace_not_found"
100       redirect_to :action => "list"
101     end
102   rescue ActiveRecord::RecordNotFound
103     flash[:error] = t "trace.view.trace_not_found"
104     redirect_to :action => "list"
105   end
106
107   def create
108     if request.post?
109       logger.info(params[:trace][:gpx_file].class.name)
110
111       if params[:trace][:gpx_file].respond_to?(:read)
112         begin
113           do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
114                     params[:trace][:description], params[:trace][:visibility])
115         rescue StandardError => ex
116           logger.debug ex
117         end
118
119         if @trace.id
120           flash[:notice] = t "trace.create.trace_uploaded"
121
122           flash[:warning] = t "trace.trace_header.traces_waiting", :count => current_user.traces.where(:inserted => false).count if current_user.traces.where(:inserted => false).count > 4
123
124           redirect_to :action => :list, :display_name => current_user.display_name
125         end
126       else
127         @trace = Trace.new(:name => "Dummy",
128                            :tagstring => params[:trace][:tagstring],
129                            :description => params[:trace][:description],
130                            :visibility => params[:trace][:visibility],
131                            :inserted => false, :user => current_user,
132                            :timestamp => Time.now.getutc)
133         @trace.valid?
134         @trace.errors.add(:gpx_file, "can't be blank")
135       end
136     else
137       @trace = Trace.new(:visibility => default_visibility)
138     end
139
140     @title = t "trace.create.upload_trace"
141   end
142
143   def data
144     trace = Trace.find(params[:id])
145
146     if trace.visible? && (trace.public? || (current_user && current_user == trace.user))
147       if Acl.no_trace_download(request.remote_ip)
148         head :forbidden
149       elsif request.format == Mime[:xml]
150         send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
151       elsif request.format == Mime[:gpx]
152         send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
153       else
154         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
155       end
156     else
157       head :not_found
158     end
159   rescue ActiveRecord::RecordNotFound
160     head :not_found
161   end
162
163   def edit
164     @trace = Trace.find(params[:id])
165
166     if !@trace.visible?
167       head :not_found
168     elsif current_user.nil? || @trace.user != current_user
169       head :forbidden
170     else
171       @title = t "trace.edit.title", :name => @trace.name
172
173       if request.post? && params[:trace]
174         @trace.description = params[:trace][:description]
175         @trace.tagstring = params[:trace][:tagstring]
176         @trace.visibility = params[:trace][:visibility]
177         redirect_to :action => "view", :display_name => current_user.display_name if @trace.save
178       end
179     end
180   rescue ActiveRecord::RecordNotFound
181     head :not_found
182   end
183
184   def delete
185     trace = Trace.find(params[:id])
186
187     if !trace.visible?
188       head :not_found
189     elsif current_user.nil? || (trace.user != current_user && !current_user.administrator? && !current_user.moderator?)
190       head :forbidden
191     else
192       trace.visible = false
193       trace.save
194       flash[:notice] = t "trace.delete.scheduled_for_deletion"
195       redirect_to :action => :list, :display_name => trace.user.display_name
196     end
197   rescue ActiveRecord::RecordNotFound
198     head :not_found
199   end
200
201   def georss
202     @traces = Trace.visible_to_all.visible
203
204     @traces = @traces.joins(:user).where(:users => { :display_name => params[:display_name] }) if params[:display_name]
205
206     @traces = @traces.tagged(params[:tag]) if params[:tag]
207     @traces = @traces.order("timestamp DESC")
208     @traces = @traces.limit(20)
209     @traces = @traces.includes(:user)
210   end
211
212   def picture
213     trace = Trace.find(params[:id])
214
215     if trace.visible? && trace.inserted?
216       if trace.public? || (current_user && current_user == trace.user)
217         expires_in 7.days, :private => !trace.public?, :public => trace.public?
218         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => "image/gif", :disposition => "inline")
219       else
220         head :forbidden
221       end
222     else
223       head :not_found
224     end
225   rescue ActiveRecord::RecordNotFound
226     head :not_found
227   end
228
229   def icon
230     trace = Trace.find(params[:id])
231
232     if trace.visible? && trace.inserted?
233       if trace.public? || (current_user && current_user == trace.user)
234         expires_in 7.days, :private => !trace.public?, :public => trace.public?
235         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => "image/gif", :disposition => "inline")
236       else
237         head :forbidden
238       end
239     else
240       head :not_found
241     end
242   rescue ActiveRecord::RecordNotFound
243     head :not_found
244   end
245
246   def api_read
247     trace = Trace.visible.find(params[:id])
248
249     if trace.public? || trace.user == current_user
250       render :xml => trace.to_xml.to_s
251     else
252       head :forbidden
253     end
254   end
255
256   def api_update
257     trace = Trace.visible.find(params[:id])
258
259     if trace.user == current_user
260       trace.update_from_xml(request.raw_post)
261       trace.save!
262
263       head :ok
264     else
265       head :forbidden
266     end
267   end
268
269   def api_delete
270     trace = Trace.visible.find(params[:id])
271
272     if trace.user == current_user
273       trace.visible = false
274       trace.save!
275
276       head :ok
277     else
278       head :forbidden
279     end
280   end
281
282   def api_data
283     trace = Trace.visible.find(params[:id])
284
285     if trace.public? || trace.user == current_user
286       if request.format == Mime[:xml]
287         send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
288       elsif request.format == Mime[:gpx]
289         send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
290       else
291         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
292       end
293     else
294       head :forbidden
295     end
296   end
297
298   def api_create
299     tags = params[:tags] || ""
300     description = params[:description] || ""
301     visibility = params[:visibility]
302
303     if visibility.nil?
304       visibility = if params[:public] && params[:public].to_i.nonzero?
305                      "public"
306                    else
307                      "private"
308                    end
309     end
310
311     if params[:file].respond_to?(:read)
312       do_create(params[:file], tags, description, visibility)
313
314       if @trace.id
315         render :plain => @trace.id.to_s
316       elsif @trace.valid?
317         head :internal_server_error
318       else
319         head :bad_request
320       end
321     else
322       head :bad_request
323     end
324   end
325
326   private
327
328   def do_create(file, tags, description, visibility)
329     # Sanitise the user's filename
330     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, "_")
331
332     # Get a temporary filename...
333     filename = "/tmp/#{rand}"
334
335     # ...and save the uploaded file to that location
336     File.open(filename, "wb") { |f| f.write(file.read) }
337
338     # Create the trace object, falsely marked as already
339     # inserted to stop the import daemon trying to load it
340     @trace = Trace.new(
341       :name => name,
342       :tagstring => tags,
343       :description => description,
344       :visibility => visibility,
345       :inserted => true,
346       :user => current_user,
347       :timestamp => Time.now.getutc
348     )
349
350     Trace.transaction do
351       begin
352         # Save the trace object
353         @trace.save!
354
355         # Rename the temporary file to the final name
356         FileUtils.mv(filename, @trace.trace_name)
357       rescue StandardError
358         # Remove the file as we have failed to update the database
359         FileUtils.rm_f(filename)
360
361         # Pass the exception on
362         raise
363       end
364
365       begin
366         # Clear the inserted flag to make the import daemon load the trace
367         @trace.inserted = false
368         @trace.save!
369       rescue StandardError
370         # Remove the file as we have failed to update the database
371         FileUtils.rm_f(@trace.trace_name)
372
373         # Pass the exception on
374         raise
375       end
376     end
377
378     # Finally save the user's preferred privacy level
379     if pref = current_user.preferences.where(:k => "gps.trace.visibility").first
380       pref.v = visibility
381       pref.save
382     else
383       current_user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
384     end
385   end
386
387   def offline_warning
388     flash.now[:warning] = t "trace.offline_warning.message" if STATUS == :gpx_offline
389   end
390
391   def offline_redirect
392     redirect_to :action => :offline if STATUS == :gpx_offline
393   end
394
395   def default_visibility
396     visibility = current_user.preferences.where(:k => "gps.trace.visibility").first
397
398     if visibility
399       visibility.v
400     elsif current_user.preferences.where(:k => "gps.trace.public", :v => "default").first.nil?
401       "private"
402     else
403       "public"
404     end
405   end
406 end