1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
7 before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
8 before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
9 before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
10 after_filter :compress_output
12 # Help methods for checking boundary sanity and area size
15 # Helper methods for checking consistency
16 include ConsistencyValidations
18 # Create a changeset from XML.
21 cs = Changeset.from_xml(request.raw_post, true)
26 render :text => cs.id.to_s, :content_type => "text/plain"
28 render :nothing => true, :status => :bad_request
31 render :nothing => true, :status => :method_not_allowed
36 # Return XML giving the basic info about the changeset. Does not
37 # return anything about the nodes, ways and relations in the changeset.
40 changeset = Changeset.find(params[:id])
41 render :text => changeset.to_xml.to_s, :content_type => "text/xml"
42 rescue ActiveRecord::RecordNotFound
43 render :nothing => true, :status => :not_found
48 # marks a changeset as closed. this may be called multiple times
49 # on the same changeset, so is idempotent.
52 render :nothing => true, :status => :method_not_allowed
56 changeset = Changeset.find(params[:id])
57 check_changeset_consistency(changeset, @user)
59 # to close the changeset, we'll just set its closed_at time to
60 # now. this might not be enough if there are concurrency issues,
61 # but we'll have to wait and see.
62 changeset.set_closed_time_now
65 render :nothing => true
66 rescue ActiveRecord::RecordNotFound
67 render :nothing => true, :status => :not_found
68 rescue OSM::APIError => ex
73 # insert a (set of) points into a changeset bounding box. this can only
74 # increase the size of the bounding box. this is a hint that clients can
75 # set either before uploading a large number of changes, or changes that
76 # the client (but not the server) knows will affect areas further away.
78 # only allow POST requests, because although this method is
79 # idempotent, there is no "document" to PUT really...
81 cs = Changeset.find(params[:id])
82 check_changeset_consistency(cs, @user)
84 # keep an array of lons and lats
88 # the request is in pseudo-osm format... this is kind-of an
89 # abuse, maybe should change to some other format?
90 doc = XML::Parser.string(request.raw_post).parse
91 doc.find("//osm/node").each do |n|
92 lon << n['lon'].to_f * GeoRecord::SCALE
93 lat << n['lat'].to_f * GeoRecord::SCALE
96 # add the existing bounding box to the lon-lat array
97 lon << cs.min_lon unless cs.min_lon.nil?
98 lat << cs.min_lat unless cs.min_lat.nil?
99 lon << cs.max_lon unless cs.max_lon.nil?
100 lat << cs.max_lat unless cs.max_lat.nil?
102 # collapse the arrays to minimum and maximum
103 cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
104 lon.min, lat.min, lon.max, lat.max
106 # save the larger bounding box and return the changeset, which
107 # will include the bigger bounding box.
109 render :text => cs.to_xml.to_s, :content_type => "text/xml"
112 render :nothing => true, :status => :method_not_allowed
115 rescue ActiveRecord::RecordNotFound
116 render :nothing => true, :status => :not_found
117 rescue OSM::APIError => ex
118 render ex.render_opts
122 # Upload a diff in a single transaction.
124 # This means that each change within the diff must succeed, i.e: that
125 # each version number mentioned is still current. Otherwise the entire
126 # transaction *must* be rolled back.
128 # Furthermore, each element in the diff can only reference the current
131 # Returns: a diffResult document, as described in
132 # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
134 # only allow POST requests, as the upload method is most definitely
135 # not idempotent, as several uploads with placeholder IDs will have
136 # different side-effects.
137 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
139 render :nothing => true, :status => :method_not_allowed
143 changeset = Changeset.find(params[:id])
144 check_changeset_consistency(changeset, @user)
146 diff_reader = DiffReader.new(request.raw_post, changeset)
147 Changeset.transaction do
148 result = diff_reader.commit
149 render :text => result.to_s, :content_type => "text/xml"
152 rescue ActiveRecord::RecordNotFound
153 render :nothing => true, :status => :not_found
154 rescue OSM::APIError => ex
155 render ex.render_opts
159 # download the changeset as an osmChange document.
161 # to make it easier to revert diffs it would be better if the osmChange
162 # format were reversible, i.e: contained both old and new versions of
163 # modified elements. but it doesn't at the moment...
165 # this method cannot order the database changes fully (i.e: timestamp and
166 # version number may be too coarse) so the resulting diff may not apply
167 # to a different database. however since changesets are not atomic this
168 # behaviour cannot be guaranteed anyway and is the result of a design
171 changeset = Changeset.find(params[:id])
173 # get all the elements in the changeset and stick them in a big array.
174 elements = [changeset.old_nodes,
176 changeset.old_relations].flatten
178 # sort the elements by timestamp and version number, as this is the
179 # almost sensible ordering available. this would be much nicer if
180 # global (SVN-style) versioning were used - then that would be
182 elements.sort! do |a, b|
183 if (a.timestamp == b.timestamp)
184 a.version <=> b.version
186 a.timestamp <=> b.timestamp
190 # create an osmChange document for the output
191 result = OSM::API.new.get_xml_doc
192 result.root.name = "osmChange"
194 # generate an output element for each operation. note: we avoid looking
195 # at the history because it is simpler - but it would be more correct to
196 # check these assertions.
197 elements.each do |elt|
199 if (elt.version == 1)
200 # first version, so it must be newly-created.
201 created = XML::Node.new "create"
202 created << elt.to_xml_node
204 # get the previous version from the element history
205 prev_elt = elt.class.find(:first, :conditions =>
206 ['id = ? and version = ?',
207 elt.id, elt.version])
209 # if the element isn't visible then it must have been deleted, so
210 # output the *previous* XML
211 deleted = XML::Node.new "delete"
212 deleted << prev_elt.to_xml_node
214 # must be a modify, for which we don't need the previous version
216 modified = XML::Node.new "modify"
217 modified << elt.to_xml_node
222 render :text => result.to_s, :content_type => "text/xml"
224 rescue ActiveRecord::RecordNotFound
225 render :nothing => true, :status => :not_found
226 rescue OSM::APIError => ex
227 render ex.render_opts
231 # query changesets by bounding box, time, user or open/closed status.
233 # create the conditions that the user asked for. some or all of
235 conditions = conditions_bbox(params['bbox'])
236 conditions = cond_merge conditions, conditions_user(params['user'])
237 conditions = cond_merge conditions, conditions_time(params['time'])
238 conditions = cond_merge conditions, conditions_open(params['open'])
240 # create the results document
241 results = OSM::API.new.get_xml_doc
243 # add all matching changesets to the XML results document
245 :conditions => conditions,
247 :order => 'created_at desc').each do |cs|
248 results.root << cs.to_xml_node
251 render :text => results.to_s, :content_type => "text/xml"
253 rescue ActiveRecord::RecordNotFound
254 render :nothing => true, :status => :not_found
255 rescue OSM::APIError => ex
256 render ex.render_opts
260 # updates a changeset's tags. none of the changeset's attributes are
261 # user-modifiable, so they will be ignored.
263 # changesets are not (yet?) versioned, so we don't have to deal with
264 # history tables here. changesets are locked to a single user, however.
266 # after succesful update, returns the XML of the changeset.
268 # request *must* be a PUT.
270 render :nothing => true, :status => :method_not_allowed
274 changeset = Changeset.find(params[:id])
275 new_changeset = Changeset.from_xml(request.raw_post)
277 unless new_changeset.nil?
278 check_changeset_consistency(changeset, @user)
279 changeset.update_from(new_changeset, @user)
280 render :text => changeset.to_xml, :mime_type => "text/xml"
283 render :nothing => true, :status => :bad_request
286 rescue ActiveRecord::RecordNotFound
287 render :nothing => true, :status => :not_found
288 rescue OSM::APIError => ex
289 render ex.render_opts
293 #------------------------------------------------------------
294 # utility functions below.
295 #------------------------------------------------------------
298 # merge two conditions
303 return [ a_str + " and " + b_str ] + a + b
312 # if a bounding box was specified then parse it and do some sanity
313 # checks. this is mostly the same as the map call, but without the
315 def conditions_bbox(bbox)
317 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
318 bbox = sanitise_boundaries(bbox.split(/,/))
319 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
320 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
321 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
322 bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
329 # restrict changesets to those by a particular user
330 def conditions_user(user)
332 # user input checking, we don't have any UIDs < 1
333 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
335 u = User.find(user.to_i)
336 # should be able to get changesets of public users only, or
337 # our own changesets regardless of public-ness.
338 unless u.data_public?
339 # get optional user auth stuff so that users can see their own
340 # changesets if they're non-public
343 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
345 return ['user_id = ?', u.id]
352 # restrict changes to those during a particular time period
353 def conditions_time(time)
355 # if there is a range, i.e: comma separated, then the first is
356 # low, second is high - same as with bounding boxes.
357 if time.count(',') == 1
358 # check that we actually have 2 elements in the array
359 times = time.split(/,/)
360 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
362 from, to = times.collect { |t| DateTime.parse(t) }
363 return ['closed_at >= ? and created_at <= ?', from, to]
365 # if there is no comma, assume its a lower limit on time
366 return ['closed_at >= ?', DateTime.parse(time)]
371 # stupid DateTime seems to throw both of these for bad parsing, so
372 # we have to catch both and ensure the correct code path is taken.
373 rescue ArgumentError => ex
374 raise OSM::APIBadUserInput.new(ex.message.to_s)
375 rescue RuntimeError => ex
376 raise OSM::APIBadUserInput.new(ex.message.to_s)
380 # restrict changes to those which are open
381 def conditions_open(open)
382 return open.nil? ? nil : ['closed_at >= ?', DateTime.now]