]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
Force openid callbacks to use GET to avoid CSRF validation issues
[rails.git] / app / controllers / api_controller.rb
1 class ApiController < ApplicationController
2
3   skip_before_filter :verify_authenticity_token
4   before_filter :check_api_readable, :except => [:capabilities]
5   after_filter :compress_output
6   around_filter :api_call_handle_error, :api_call_timeout
7
8   # Help methods for checking boundary sanity and area size
9   include MapBoundary
10
11   # Get an XML response containing a list of tracepoints that have been uploaded
12   # within the specified bounding box, and in the specified page.
13   def trackpoints
14     #retrieve the page number
15     page = params['page'].to_s.to_i
16
17     unless page >= 0
18         report_error("Page number must be greater than or equal to 0")
19         return
20     end
21
22     offset = page * TRACEPOINTS_PER_PAGE
23
24     # Figure out the bbox
25     bbox = params['bbox']
26     unless bbox and bbox.count(',') == 3
27       report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
28       return
29     end
30
31     bbox = bbox.split(',')
32     min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
33     # check boundary is sane and area within defined
34     # see /config/application.yml
35     begin
36       check_boundaries(min_lon, min_lat, max_lon, max_lat)
37     rescue Exception => err
38       report_error(err.message)
39       return
40     end
41
42     # get all the points
43     points = Tracepoint.bbox(min_lat, min_lon, max_lat, max_lon).offset(offset).limit(TRACEPOINTS_PER_PAGE).order("gpx_id DESC, trackid ASC, timestamp ASC")
44
45     doc = XML::Document.new
46     doc.encoding = XML::Encoding::UTF_8
47     root = XML::Node.new 'gpx'
48     root['version'] = '1.0'
49     root['creator'] = 'OpenStreetMap.org'
50     root['xmlns'] = "http://www.topografix.com/GPX/1/0"
51     
52     doc.root = root
53
54     # initialise these variables outside of the loop so that they
55     # stay in scope and don't get free'd up by the GC during the
56     # loop.
57     gpx_id = -1
58     trackid = -1
59     track = nil
60     trkseg = nil
61     anon_track = nil
62     anon_trkseg = nil
63     gpx_file = nil
64     timestamps = false
65
66     points.each do |point|
67       if gpx_id != point.gpx_id
68         gpx_id = point.gpx_id
69         trackid = -1
70         gpx_file = Trace.find(gpx_id)
71
72         if gpx_file.trackable?
73           track = XML::Node.new 'trk'
74           doc.root << track
75           timestamps = true
76
77           if gpx_file.identifiable?
78             track << (XML::Node.new("name") << gpx_file.name)
79             track << (XML::Node.new("desc") << gpx_file.description)
80             track << (XML::Node.new("url") << url_for(:controller => 'trace', :action => 'view', :id => gpx_file.id))
81           end
82         else
83           # use the anonymous track segment if the user hasn't allowed
84           # their GPX points to be tracked.
85           timestamps = false
86           if anon_track.nil? 
87             anon_track = XML::Node.new 'trk'
88             doc.root << anon_track
89           end
90           track = anon_track
91         end
92       end
93       
94       if trackid != point.trackid
95         if gpx_file.trackable?
96           trkseg = XML::Node.new 'trkseg'
97           track << trkseg
98           trackid = point.trackid
99         else
100           if anon_trkseg.nil? 
101             anon_trkseg = XML::Node.new 'trkseg'
102             anon_track << anon_trkseg
103           end
104           trkseg = anon_trkseg
105         end
106       end
107
108       trkseg << point.to_xml_node(timestamps)
109     end
110
111     response.headers["Content-Disposition"] = "attachment; filename=\"tracks.gpx\""
112
113     render :text => doc.to_s, :content_type => "text/xml"
114   end
115
116   # This is probably the most common call of all. It is used for getting the 
117   # OSM data for a specified bounding box, usually for editing. First the
118   # bounding box (bbox) is checked to make sure that it is sane. All nodes 
119   # are searched, then all the ways that reference those nodes are found.
120   # All Nodes that are referenced by those ways are fetched and added to the list
121   # of nodes.
122   # Then all the relations that reference the already found nodes and ways are
123   # fetched. All the nodes and ways that are referenced by those ways are then 
124   # fetched. Finally all the xml is returned.
125   def map
126     # Figure out the bbox
127     bbox = params['bbox']
128
129     unless bbox and bbox.count(',') == 3
130       # alternatively: report_error(TEXT['boundary_parameter_required']
131       report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
132       return
133     end
134
135     bbox = bbox.split(',')
136
137     min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
138
139     # check boundary is sane and area within defined
140     # see /config/application.yml
141     begin
142       check_boundaries(min_lon, min_lat, max_lon, max_lat)
143     rescue Exception => err
144       report_error(err.message)
145       return
146     end
147
148     # FIXME um why is this area using a different order for the lat/lon from above???
149     @nodes = Node.bbox(min_lat, min_lon, max_lat, max_lon).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES+1)
150     # get all the nodes, by tag not yet working, waiting for change from NickB
151     # need to be @nodes (instance var) so tests in /spec can be performed
152     #@nodes = Node.search(bbox, params[:tag])
153
154     node_ids = @nodes.collect(&:id)
155     if node_ids.length > MAX_NUMBER_OF_NODES
156       report_error("You requested too many nodes (limit is #{MAX_NUMBER_OF_NODES}). Either request a smaller area, or use planet.osm")
157       return
158     end
159     if node_ids.length == 0
160       render :text => "<osm version='#{API_VERSION}' generator='#{GENERATOR}'></osm>", :content_type => "text/xml"
161       return
162     end
163
164     doc = OSM::API.new.get_xml_doc
165
166     # add bounds
167     bounds = XML::Node.new 'bounds'
168     bounds['minlat'] = min_lat.to_s
169     bounds['minlon'] = min_lon.to_s
170     bounds['maxlat'] = max_lat.to_s
171     bounds['maxlon'] = max_lon.to_s
172     doc.root << bounds
173
174     # get ways
175     # find which ways are needed
176     ways = Array.new
177     if node_ids.length > 0
178       way_nodes = WayNode.find_all_by_node_id(node_ids)
179       way_ids = way_nodes.collect { |way_node| way_node.id[0] }
180       ways = Way.find(way_ids, :include => [:way_nodes, :way_tags])
181
182       list_of_way_nodes = ways.collect { |way|
183         way.way_nodes.collect { |way_node| way_node.node_id }
184       }
185       list_of_way_nodes.flatten!
186
187     else
188       list_of_way_nodes = Array.new
189     end
190
191     # - [0] in case some thing links to node 0 which doesn't exist. Shouldn't actually ever happen but it does. FIXME: file a ticket for this
192     nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
193
194     if nodes_to_fetch.length > 0
195       @nodes += Node.includes(:node_tags).find(nodes_to_fetch)
196     end
197
198     visible_nodes = {}
199     changeset_cache = {}
200     user_display_name_cache = {}
201
202     @nodes.each do |node|
203       if node.visible?
204         doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
205         visible_nodes[node.id] = node
206       end
207     end
208
209     way_ids = Array.new
210     ways.each do |way|
211       if way.visible?
212         doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
213         way_ids << way.id
214       end
215     end 
216
217     relations = Relation.nodes(visible_nodes.keys).visible +
218                 Relation.ways(way_ids).visible
219
220     # we do not normally return the "other" partners referenced by an relation, 
221     # e.g. if we return a way A that is referenced by relation X, and there's 
222     # another way B also referenced, that is not returned. But we do make 
223     # an exception for cases where an relation references another *relation*; 
224     # in that case we return that as well (but we don't go recursive here)
225     relations += Relation.relations(relations.collect { |r| r.id }).visible
226
227     # this "uniq" may be slightly inefficient; it may be better to first collect and output
228     # all node-related relations, then find the *not yet covered* way-related ones etc.
229     relations.uniq.each do |relation|
230       doc.root << relation.to_xml_node(nil, changeset_cache, user_display_name_cache)
231     end
232
233     response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
234
235     render :text => doc.to_s, :content_type => "text/xml"
236   end
237
238   # Get a list of the tiles that have changed within a specified time
239   # period
240   def changes
241     zoom = (params[:zoom] || '12').to_i
242
243     if params.include?(:start) and params.include?(:end)
244       starttime = Time.parse(params[:start])
245       endtime = Time.parse(params[:end])
246     else
247       hours = (params[:hours] || '1').to_i.hours
248       endtime = Time.now.getutc
249       starttime = endtime - hours
250     end
251
252     if zoom >= 1 and zoom <= 16 and
253        endtime > starttime and endtime - starttime <= 24.hours
254       mask = (1 << zoom) - 1
255
256       tiles = Node.where(:timestamp => starttime .. endtime).group("maptile_for_point(latitude, longitude, #{zoom})").count
257
258       doc = OSM::API.new.get_xml_doc
259       changes = XML::Node.new 'changes'
260       changes["starttime"] = starttime.xmlschema
261       changes["endtime"] = endtime.xmlschema
262
263       tiles.each do |tile, count|
264         x = (tile.to_i >> zoom) & mask
265         y = tile.to_i & mask
266
267         t = XML::Node.new 'tile'
268         t["x"] = x.to_s
269         t["y"] = y.to_s
270         t["z"] = zoom.to_s
271         t["changes"] = count.to_s
272
273         changes << t
274       end
275
276       doc.root << changes
277
278       render :text => doc.to_s, :content_type => "text/xml"
279     else
280       render :text => "Requested zoom is invalid, or the supplied start is after the end time, or the start duration is more than 24 hours", :status => :bad_request
281     end
282   end
283
284   # External apps that use the api are able to query the api to find out some 
285   # parameters of the API. It currently returns: 
286   # * minimum and maximum API versions that can be used.
287   # * maximum area that can be requested in a bbox request in square degrees
288   # * number of tracepoints that are returned in each tracepoints page
289   def capabilities
290     doc = OSM::API.new.get_xml_doc
291
292     api = XML::Node.new 'api'
293     version = XML::Node.new 'version'
294     version['minimum'] = "#{API_VERSION}";
295     version['maximum'] = "#{API_VERSION}";
296     api << version
297     area = XML::Node.new 'area'
298     area['maximum'] = MAX_REQUEST_AREA.to_s;
299     api << area
300     tracepoints = XML::Node.new 'tracepoints'
301     tracepoints['per_page'] = TRACEPOINTS_PER_PAGE.to_s
302     api << tracepoints
303     waynodes = XML::Node.new 'waynodes'
304     waynodes['maximum'] = MAX_NUMBER_OF_WAY_NODES.to_s
305     api << waynodes
306     changesets = XML::Node.new 'changesets'
307     changesets['maximum_elements'] = Changeset::MAX_ELEMENTS.to_s
308     api << changesets
309     timeout = XML::Node.new 'timeout'
310     timeout['seconds'] = API_TIMEOUT.to_s
311     api << timeout
312     
313     doc.root << api
314
315     render :text => doc.to_s, :content_type => "text/xml"
316   end
317 end