]> git.openstreetmap.org Git - rails.git/blob - app/controllers/trace_controller.rb
There was no "Sorry not found" message for changesets so
[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  
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.visibility in ('public', 'identifiable') OR gpx_files.user_id = ?)", @user.id] #1
49       else
50         conditions  = ["gpx_files.visibility in ('public', 'identifiable')"] #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.visibility in ('public', 'identifiable') AND gpx_files.user_id = ?", 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     visibility = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
102     if visibility
103       @trace.visibility = visibility.v
104     elsif @user.preferences.find(:first, :conditions => {:k => "gps.trace.public", :v => "default"}).nil?
105       @trace.visibility = "private"
106     else 
107       @trace.visibility = "public"
108     end
109     list(@user, "mine")
110   end
111
112   def view
113     @trace = Trace.find(params[:id])
114
115     if @trace and @trace.visible? and
116        (@trace.public? or @trace.user == @user)
117       @title = t 'trace.view.title', :name => @trace.name
118     else
119       flash[:notice] = t 'trace.view.trace_not_found'
120       redirect_to :controller => 'trace', :action => 'list'
121     end
122   rescue ActiveRecord::RecordNotFound
123     flash[:notice] = t 'trace.view.trace_not_found'
124     redirect_to :controller => 'trace', :action => 'list'
125   end
126
127   def create
128     if params[:trace]
129       logger.info(params[:trace][:gpx_file].class.name)
130       if params[:trace][:gpx_file].respond_to?(:read)
131         do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
132                   params[:trace][:description], params[:trace][:visibility])
133
134         if @trace.id
135           logger.info("id is #{@trace.id}")
136           flash[:notice] = t 'trace.create.trace_uploaded'
137
138           redirect_to :action => 'mine'
139         end
140       else
141         @trace = Trace.new({:name => "Dummy",
142                             :tagstring => params[:trace][:tagstring],
143                             :description => params[:trace][:description],
144                             :visibility => params[:trace][:visibility],
145                             :inserted => false, :user => @user,
146                             :timestamp => Time.now.getutc})
147         @trace.valid?
148         @trace.errors.add(:gpx_file, "can't be blank")
149       end
150     end
151     @title = t 'trace.create.upload_trace'
152   end
153
154   def data
155     trace = Trace.find(params[:id])
156
157     if trace.visible? and (trace.public? or (@user and @user == trace.user))
158       if request.format == Mime::XML
159         send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => Mime::XML.to_s, :disposition => 'attachment')
160       else
161         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
162       end
163     else
164       render :nothing => true, :status => :not_found
165     end
166   rescue ActiveRecord::RecordNotFound
167     render :nothing => true, :status => :not_found
168   end
169
170   def edit
171     @trace = Trace.find(params[:id])
172
173     if @user and @trace.user == @user
174       @title = t 'trace.edit.title', :name => @trace.name
175       if params[:trace]
176         @trace.description = params[:trace][:description]
177         @trace.tagstring = params[:trace][:tagstring]
178         @trace.visibility = params[:trace][:visibility]
179         if @trace.save
180           redirect_to :action => 'view'
181         end        
182       end
183     else
184       render :nothing => true, :status => :forbidden
185     end
186   rescue ActiveRecord::RecordNotFound
187     render :nothing => true, :status => :not_found
188   end
189
190   def delete
191     trace = Trace.find(params[:id])
192
193     if @user and trace.user == @user
194       if request.post? and trace.visible?
195         trace.visible = false
196         trace.save
197         flash[:notice] = t 'trace.delete.scheduled_for_deletion'
198         redirect_to :controller => 'traces', :action => 'mine'
199       else
200         render :nothing => true, :status => :bad_request
201       end
202     else
203       render :nothing => true, :status => :forbidden
204     end
205   rescue ActiveRecord::RecordNotFound
206     render :nothing => true, :status => :not_found
207   end
208
209   def georss
210     conditions = ["gpx_files.visibility in ('public', 'identifiable')"]
211
212     if params[:display_name]
213       conditions[0] += " AND users.display_name = ?"
214       conditions << params[:display_name]
215     end
216
217     if params[:tag]
218       conditions[0] += " AND EXISTS (SELECT * FROM gpx_file_tags AS gft WHERE gft.gpx_id = gpx_files.id AND gft.tag = ?)"
219       conditions << params[:tag]
220     end
221
222     traces = Trace.find(:all, :include => :user, :conditions => conditions, 
223                         :order => "timestamp DESC", :limit => 20)
224
225     rss = OSM::GeoRSS.new
226
227     traces.each do |trace|
228       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)
229     end
230
231     render :text => rss.to_s, :content_type => "application/rss+xml"
232   end
233
234   def picture
235     trace = Trace.find(params[:id])
236
237     if trace.inserted?
238       if trace.public? or (@user and @user == trace.user)
239         expires_in 7.days, :private => !trace.public?, :public => trace.public?
240         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline')
241       else
242         render :nothing => true, :status => :forbidden
243       end
244     else
245       render :nothing => true, :status => :not_found
246     end
247   rescue ActiveRecord::RecordNotFound
248     render :nothing => true, :status => :not_found
249   end
250
251   def icon
252     trace = Trace.find(params[:id])
253
254     if trace.inserted?
255       if trace.public? or (@user and @user == trace.user)
256         expires_in 7.days, :private => !trace.public?, :public => trace.public?
257         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline')
258       else
259         render :nothing => true, :status => :forbidden
260       end
261     else
262       render :nothing => true, :status => :not_found
263     end
264   rescue ActiveRecord::RecordNotFound
265     render :nothing => true, :status => :not_found
266   end
267
268   def api_details
269     trace = Trace.find(params[:id])
270
271     if trace.public? or trace.user == @user
272       render :text => trace.to_xml.to_s, :content_type => "text/xml"
273     else
274       render :nothing => true, :status => :forbidden
275     end
276   rescue ActiveRecord::RecordNotFound
277     render :nothing => true, :status => :not_found
278   end
279
280   def api_data
281     trace = Trace.find(params[:id])
282
283     if trace.public? or trace.user == @user
284       send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
285     else
286       render :nothing => true, :status => :forbidden
287     end
288   rescue ActiveRecord::RecordNotFound
289     render :nothing => true, :status => :not_found
290   end
291
292   def api_create
293     if request.post?
294       tags = params[:tags] || ""
295       description = params[:description] || ""
296       visibility = params[:visibility]
297
298       if visibility.nil?
299         if params[:public]
300           visibility = "public"
301         else
302           visibility = "private"
303         end
304       end
305
306       if params[:file].respond_to?(:read)
307         do_create(params[:file], tags, description, visibility)
308
309         if @trace.id
310           render :text => @trace.id.to_s, :content_type => "text/plain"
311         elsif @trace.valid?
312           render :nothing => true, :status => :internal_server_error
313         else
314           render :nothing => true, :status => :bad_request
315         end
316       else
317         render :nothing => true, :status => :bad_request
318       end
319     else
320       render :nothing => true, :status => :method_not_allowed
321     end
322   end
323
324 private
325
326   def do_create(file, tags, description, visibility)
327     # Sanitise the user's filename
328     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, '_')
329
330     # Get a temporary filename...
331     filename = "/tmp/#{rand}"
332
333     # ...and save the uploaded file to that location
334     File.open(filename, "w") { |f| f.write(file.read) }
335
336     # Create the trace object, falsely marked as already
337     # inserted to stop the import daemon trying to load it
338     @trace = Trace.new({
339       :name => name,
340       :tagstring => tags,
341       :description => description,
342       :visibility => visibility,
343       :inserted => true,
344       :user => @user,
345       :timestamp => Time.now.getutc
346     })
347
348     # Save the trace object
349     if @trace.save
350       # Rename the temporary file to the final name
351       FileUtils.mv(filename, @trace.trace_name)
352
353       # Clear the inserted flag to make the import daemon load the trace
354       @trace.inserted = false
355       @trace.save!
356     else
357       # Remove the file as we have failed to update the database
358       FileUtils.rm_f(filename)
359     end
360     
361     # Finally save the user's preferred previacy level
362     if pref = @user.preferences.find(:first, :conditions => {:k => "gps.trace.visibility"})
363       pref.v = visibility
364       pref.save
365     else
366       @user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
367     end
368     
369   end
370
371 end