]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
Instruct iD to load gpx file
[rails.git] / app / controllers / changeset_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 class ChangesetController < ApplicationController
4   layout 'site'
5   require 'xml/libxml'
6
7   skip_before_filter :verify_authenticity_token, :except => [:list]
8   before_filter :authorize_web, :only => [:list, :feed]
9   before_filter :set_locale, :only => [:list, :feed]
10   before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
11   before_filter :require_allow_write_api, :only => [:create, :update, :delete, :upload, :include, :close]
12   before_filter :require_public_data, :only => [:create, :update, :delete, :upload, :include, :close]
13   before_filter :check_api_writable, :only => [:create, :update, :delete, :upload, :include]
14   before_filter :check_api_readable, :except => [:create, :update, :delete, :upload, :download, :query, :list, :feed]
15   before_filter(:only => [:list, :feed]) { |c| c.check_database_readable(true) }
16   after_filter :compress_output
17   around_filter :api_call_handle_error, :except => [:list, :feed]
18   around_filter :web_timeout, :only => [:list, :feed]
19
20   # Helper methods for checking consistency
21   include ConsistencyValidations
22
23   # Create a changeset from XML.
24   def create
25     assert_method :put
26
27     cs = Changeset.from_xml(request.raw_post, true)
28
29     # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
30     cs.user_id = @user.id
31     cs.save_with_tags!
32     render :text => cs.id.to_s, :content_type => "text/plain"
33   end
34
35   ##
36   # Return XML giving the basic info about the changeset. Does not
37   # return anything about the nodes, ways and relations in the changeset.
38   def read
39     changeset = Changeset.find(params[:id])
40     render :text => changeset.to_xml.to_s, :content_type => "text/xml"
41   end
42
43   ##
44   # marks a changeset as closed. this may be called multiple times
45   # on the same changeset, so is idempotent.
46   def close
47     assert_method :put
48
49     changeset = Changeset.find(params[:id])
50     check_changeset_consistency(changeset, @user)
51
52     # to close the changeset, we'll just set its closed_at time to
53     # now. this might not be enough if there are concurrency issues,
54     # but we'll have to wait and see.
55     changeset.set_closed_time_now
56
57     changeset.save!
58     render :text => ""
59   end
60
61   ##
62   # insert a (set of) points into a changeset bounding box. this can only
63   # increase the size of the bounding box. this is a hint that clients can
64   # set either before uploading a large number of changes, or changes that
65   # the client (but not the server) knows will affect areas further away.
66   def expand_bbox
67     # only allow POST requests, because although this method is
68     # idempotent, there is no "document" to PUT really...
69     assert_method :post
70
71     cs = Changeset.find(params[:id])
72     check_changeset_consistency(cs, @user)
73
74     # keep an array of lons and lats
75     lon = Array.new
76     lat = Array.new
77
78     # the request is in pseudo-osm format... this is kind-of an
79     # abuse, maybe should change to some other format?
80     doc = XML::Parser.string(request.raw_post).parse
81     doc.find("//osm/node").each do |n|
82       lon << n['lon'].to_f * GeoRecord::SCALE
83       lat << n['lat'].to_f * GeoRecord::SCALE
84     end
85
86     # add the existing bounding box to the lon-lat array
87     lon << cs.min_lon unless cs.min_lon.nil?
88     lat << cs.min_lat unless cs.min_lat.nil?
89     lon << cs.max_lon unless cs.max_lon.nil?
90     lat << cs.max_lat unless cs.max_lat.nil?
91
92     # collapse the arrays to minimum and maximum
93     cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
94       lon.min, lat.min, lon.max, lat.max
95
96     # save the larger bounding box and return the changeset, which
97     # will include the bigger bounding box.
98     cs.save!
99     render :text => cs.to_xml.to_s, :content_type => "text/xml"
100   end
101
102   ##
103   # Upload a diff in a single transaction.
104   #
105   # This means that each change within the diff must succeed, i.e: that
106   # each version number mentioned is still current. Otherwise the entire
107   # transaction *must* be rolled back.
108   #
109   # Furthermore, each element in the diff can only reference the current
110   # changeset.
111   #
112   # Returns: a diffResult document, as described in
113   # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
114   def upload
115     # only allow POST requests, as the upload method is most definitely
116     # not idempotent, as several uploads with placeholder IDs will have
117     # different side-effects.
118     # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
119     assert_method :post
120
121     changeset = Changeset.find(params[:id])
122     check_changeset_consistency(changeset, @user)
123
124     diff_reader = DiffReader.new(request.raw_post, changeset)
125     Changeset.transaction do
126       result = diff_reader.commit
127       render :text => result.to_s, :content_type => "text/xml"
128     end
129   end
130
131   ##
132   # download the changeset as an osmChange document.
133   #
134   # to make it easier to revert diffs it would be better if the osmChange
135   # format were reversible, i.e: contained both old and new versions of
136   # modified elements. but it doesn't at the moment...
137   #
138   # this method cannot order the database changes fully (i.e: timestamp and
139   # version number may be too coarse) so the resulting diff may not apply
140   # to a different database. however since changesets are not atomic this
141   # behaviour cannot be guaranteed anyway and is the result of a design
142   # choice.
143   def download
144     changeset = Changeset.find(params[:id])
145
146     # get all the elements in the changeset which haven't been redacted
147     # and stick them in a big array.
148     elements = [changeset.old_nodes.unredacted,
149                 changeset.old_ways.unredacted,
150                 changeset.old_relations.unredacted].flatten
151
152     # sort the elements by timestamp and version number, as this is the
153     # almost sensible ordering available. this would be much nicer if
154     # global (SVN-style) versioning were used - then that would be
155     # unambiguous.
156     elements.sort! do |a, b|
157       if (a.timestamp == b.timestamp)
158         a.version <=> b.version
159       else
160         a.timestamp <=> b.timestamp
161       end
162     end
163
164     # create changeset and user caches
165     changeset_cache = {}
166     user_display_name_cache = {}
167
168     # create an osmChange document for the output
169     result = OSM::API.new.get_xml_doc
170     result.root.name = "osmChange"
171
172     # generate an output element for each operation. note: we avoid looking
173     # at the history because it is simpler - but it would be more correct to
174     # check these assertions.
175     elements.each do |elt|
176       result.root <<
177         if (elt.version == 1)
178           # first version, so it must be newly-created.
179           created = XML::Node.new "create"
180           created << elt.to_xml_node(changeset_cache, user_display_name_cache)
181         else
182           unless elt.visible
183             # if the element isn't visible then it must have been deleted
184             deleted = XML::Node.new "delete"
185             deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
186           else
187             # must be a modify
188             modified = XML::Node.new "modify"
189             modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
190           end
191         end
192     end
193
194     render :text => result.to_s, :content_type => "text/xml"
195   end
196
197   ##
198   # query changesets by bounding box, time, user or open/closed status.
199   def query
200     # find any bounding box
201     if params['bbox']
202       bbox = BoundingBox.from_bbox_params(params)
203     end
204
205     # create the conditions that the user asked for. some or all of
206     # these may be nil.
207     changesets = Changeset.all
208     changesets = conditions_bbox(changesets, bbox)
209     changesets = conditions_user(changesets, params['user'], params['display_name'])
210     changesets = conditions_time(changesets, params['time'])
211     changesets = conditions_open(changesets, params['open'])
212     changesets = conditions_closed(changesets, params['closed'])
213     changesets = conditions_ids(changesets, params['changesets'])
214
215     # create the results document
216     results = OSM::API.new.get_xml_doc
217
218     # add all matching changesets to the XML results document
219     changesets.order("created_at DESC").limit(100).each do |cs|
220       results.root << cs.to_xml_node
221     end
222
223     render :text => results.to_s, :content_type => "text/xml"
224   end
225
226   ##
227   # updates a changeset's tags. none of the changeset's attributes are
228   # user-modifiable, so they will be ignored.
229   #
230   # changesets are not (yet?) versioned, so we don't have to deal with
231   # history tables here. changesets are locked to a single user, however.
232   #
233   # after succesful update, returns the XML of the changeset.
234   def update
235     # request *must* be a PUT.
236     assert_method :put
237
238     changeset = Changeset.find(params[:id])
239     new_changeset = Changeset.from_xml(request.raw_post)
240
241     unless new_changeset.nil?
242       check_changeset_consistency(changeset, @user)
243       changeset.update_from(new_changeset, @user)
244       render :text => changeset.to_xml, :mime_type => "text/xml"
245     else
246
247       render :text => "", :status => :bad_request
248     end
249   end
250
251   ##
252   # list edits (open changesets) in reverse chronological order
253   def list
254     if request.format == :atom and params[:max_id]
255       redirect_to params.merge({ :max_id => nil }), :status => :moved_permanently
256       return
257     end
258
259     if params[:display_name]
260       user = User.find_by_display_name(params[:display_name])
261       if !user || !user.active?
262         render_unknown_user params[:display_name]
263         return
264       end
265     end
266
267     if (params[:friends] || params[:nearby]) && !@user && request.format == :html
268       require_user
269       return
270     end
271
272     if request.format == :html and !params[:list]
273       require_oauth
274       render :action => :history, :layout => map_layout
275     else
276       changesets = conditions_nonempty(Changeset.all)
277
278       if params[:display_name]
279         if user.data_public? or user == @user
280           changesets = changesets.where(:user_id => user.id)
281         else
282           changesets = changesets.where("false")
283         end
284       elsif params[:bbox]
285         changesets = conditions_bbox(changesets, BoundingBox.from_bbox_params(params))
286       elsif params[:friends] && @user
287         changesets = changesets.where(:user_id => @user.friend_users.public)
288       elsif params[:nearby] && @user
289         changesets = changesets.where(:user_id => @user.nearby)
290       end
291
292       if params[:max_id]
293         changesets = changesets.where("changesets.id <= ?", params[:max_id])
294       end
295
296       @edits = changesets.order("changesets.id DESC").limit(20).preload(:user, :changeset_tags)
297
298       render :action => :list, :layout => false
299     end
300   end
301
302   ##
303   # list edits as an atom feed
304   def feed
305     list
306   end
307
308 private
309   #------------------------------------------------------------
310   # utility functions below.
311   #------------------------------------------------------------
312
313   ##
314   # if a bounding box was specified do some sanity checks.
315   # restrict changesets to those enclosed by a bounding box
316   # we need to return both the changesets and the bounding box
317   def conditions_bbox(changesets, bbox)
318     if  bbox
319       bbox.check_boundaries
320       bbox = bbox.to_scaled
321       return changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
322                               bbox.max_lon.to_i, bbox.min_lon.to_i,
323                               bbox.max_lat.to_i, bbox.min_lat.to_i)
324     else
325       return changesets
326     end
327   end
328
329   ##
330   # restrict changesets to those by a particular user
331   def conditions_user(changesets, user, name)
332     unless user.nil? and name.nil?
333       # shouldn't provide both name and UID
334       raise OSM::APIBadUserInput.new("provide either the user ID or display name, but not both") if user and name
335
336       # use either the name or the UID to find the user which we're selecting on.
337       u = if name.nil?
338             # user input checking, we don't have any UIDs < 1
339             raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
340             u = User.find(user.to_i)
341           else
342             u = User.find_by_display_name(name)
343           end
344
345       # make sure we found a user
346       raise OSM::APINotFoundError.new if u.nil?
347
348       # should be able to get changesets of public users only, or
349       # our own changesets regardless of public-ness.
350       unless u.data_public?
351         # get optional user auth stuff so that users can see their own
352         # changesets if they're non-public
353         setup_user_auth
354
355         raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
356       end
357       return changesets.where(:user_id => u.id)
358     else
359       return changesets
360     end
361   end
362
363   ##
364   # restrict changes to those closed during a particular time period
365   def conditions_time(changesets, time)
366     unless time.nil?
367       # if there is a range, i.e: comma separated, then the first is
368       # low, second is high - same as with bounding boxes.
369       if time.count(',') == 1
370         # check that we actually have 2 elements in the array
371         times = time.split(/,/)
372         raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
373
374         from, to = times.collect { |t| DateTime.parse(t) }
375         return changesets.where("closed_at >= ? and created_at <= ?", from, to)
376       else
377         # if there is no comma, assume its a lower limit on time
378         return changesets.where("closed_at >= ?", DateTime.parse(time))
379       end
380     else
381       return changesets
382     end
383     # stupid DateTime seems to throw both of these for bad parsing, so
384     # we have to catch both and ensure the correct code path is taken.
385   rescue ArgumentError => ex
386     raise OSM::APIBadUserInput.new(ex.message.to_s)
387   rescue RuntimeError => ex
388     raise OSM::APIBadUserInput.new(ex.message.to_s)
389   end
390
391   ##
392   # return changesets which are open (haven't been closed yet)
393   # we do this by seeing if the 'closed at' time is in the future. Also if we've
394   # hit the maximum number of changes then it counts as no longer open.
395   # if parameter 'open' is nill then open and closed changesets are returned
396   def conditions_open(changesets, open)
397     if open.nil?
398       return changesets
399     else
400       return changesets.where("closed_at >= ? and num_changes <= ?",
401                               Time.now.getutc, Changeset::MAX_ELEMENTS)
402     end
403   end
404
405   ##
406   # query changesets which are closed
407   # ('closed at' time has passed or changes limit is hit)
408   def conditions_closed(changesets, closed)
409     if closed.nil?
410       return changesets
411     else
412       return changesets.where("closed_at < ? or num_changes > ?",
413                               Time.now.getutc, Changeset::MAX_ELEMENTS)
414     end
415   end
416
417   ##
418   # query changesets by a list of ids
419   # (either specified as array or comma-separated string)
420   def conditions_ids(changesets, ids)
421     if ids.nil?
422       return changesets
423     elsif ids.empty?
424       raise OSM::APIBadUserInput.new("No changesets were given to search for")
425     else
426       ids = ids.split(',').collect { |n| n.to_i }
427       return changesets.where(:id => ids)
428     end
429   end
430
431   ##
432   # eliminate empty changesets (where the bbox has not been set)
433   # this should be applied to all changeset list displays
434   def conditions_nonempty(changesets)
435     return changesets.where("num_changes > 0")
436   end
437
438 end