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