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