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