1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
7 session :off, :except => [:list]
8 before_filter :authorize_web, :only => [:list]
9 before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
10 before_filter :check_write_availability, :only => [:create, :update, :delete, :upload, :include]
11 before_filter :check_read_availability, :except => [:create, :update, :delete, :upload, :download, :query]
12 after_filter :compress_output
14 # Help methods for checking boundary sanity and area size
17 # Helper methods for checking consistency
18 include ConsistencyValidations
20 # Create a changeset from XML.
23 cs = Changeset.from_xml(request.raw_post, true)
28 render :text => cs.id.to_s, :content_type => "text/plain"
30 render :nothing => true, :status => :bad_request
33 render :nothing => true, :status => :method_not_allowed
38 # Return XML giving the basic info about the changeset. Does not
39 # return anything about the nodes, ways and relations in the changeset.
42 changeset = Changeset.find(params[:id])
43 render :text => changeset.to_xml.to_s, :content_type => "text/xml"
44 rescue ActiveRecord::RecordNotFound
45 render :nothing => true, :status => :not_found
50 # marks a changeset as closed. this may be called multiple times
51 # on the same changeset, so is idempotent.
54 render :nothing => true, :status => :method_not_allowed
58 changeset = Changeset.find(params[:id])
59 check_changeset_consistency(changeset, @user)
61 # to close the changeset, we'll just set its closed_at time to
62 # now. this might not be enough if there are concurrency issues,
63 # but we'll have to wait and see.
64 changeset.set_closed_time_now
67 render :nothing => true
68 rescue ActiveRecord::RecordNotFound
69 render :nothing => true, :status => :not_found
70 rescue OSM::APIError => ex
75 # insert a (set of) points into a changeset bounding box. this can only
76 # increase the size of the bounding box. this is a hint that clients can
77 # set either before uploading a large number of changes, or changes that
78 # the client (but not the server) knows will affect areas further away.
80 # only allow POST requests, because although this method is
81 # idempotent, there is no "document" to PUT really...
83 cs = Changeset.find(params[:id])
84 check_changeset_consistency(cs, @user)
86 # keep an array of lons and lats
90 # the request is in pseudo-osm format... this is kind-of an
91 # abuse, maybe should change to some other format?
92 doc = XML::Parser.string(request.raw_post).parse
93 doc.find("//osm/node").each do |n|
94 lon << n['lon'].to_f * GeoRecord::SCALE
95 lat << n['lat'].to_f * GeoRecord::SCALE
98 # add the existing bounding box to the lon-lat array
99 lon << cs.min_lon unless cs.min_lon.nil?
100 lat << cs.min_lat unless cs.min_lat.nil?
101 lon << cs.max_lon unless cs.max_lon.nil?
102 lat << cs.max_lat unless cs.max_lat.nil?
104 # collapse the arrays to minimum and maximum
105 cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
106 lon.min, lat.min, lon.max, lat.max
108 # save the larger bounding box and return the changeset, which
109 # will include the bigger bounding box.
111 render :text => cs.to_xml.to_s, :content_type => "text/xml"
114 render :nothing => true, :status => :method_not_allowed
117 rescue ActiveRecord::RecordNotFound
118 render :nothing => true, :status => :not_found
119 rescue OSM::APIError => ex
120 render ex.render_opts
124 # Upload a diff in a single transaction.
126 # This means that each change within the diff must succeed, i.e: that
127 # each version number mentioned is still current. Otherwise the entire
128 # transaction *must* be rolled back.
130 # Furthermore, each element in the diff can only reference the current
133 # Returns: a diffResult document, as described in
134 # http://wiki.openstreetmap.org/index.php/OSM_Protocol_Version_0.6
136 # only allow POST requests, as the upload method is most definitely
137 # not idempotent, as several uploads with placeholder IDs will have
138 # different side-effects.
139 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
141 render :nothing => true, :status => :method_not_allowed
145 changeset = Changeset.find(params[:id])
146 check_changeset_consistency(changeset, @user)
148 diff_reader = DiffReader.new(request.raw_post, changeset)
149 Changeset.transaction do
150 result = diff_reader.commit
151 render :text => result.to_s, :content_type => "text/xml"
154 rescue ActiveRecord::RecordNotFound
155 render :nothing => true, :status => :not_found
156 rescue OSM::APIError => ex
157 render ex.render_opts
161 # download the changeset as an osmChange document.
163 # to make it easier to revert diffs it would be better if the osmChange
164 # format were reversible, i.e: contained both old and new versions of
165 # modified elements. but it doesn't at the moment...
167 # this method cannot order the database changes fully (i.e: timestamp and
168 # version number may be too coarse) so the resulting diff may not apply
169 # to a different database. however since changesets are not atomic this
170 # behaviour cannot be guaranteed anyway and is the result of a design
173 changeset = Changeset.find(params[:id])
175 # get all the elements in the changeset and stick them in a big array.
176 elements = [changeset.old_nodes,
178 changeset.old_relations].flatten
180 # sort the elements by timestamp and version number, as this is the
181 # almost sensible ordering available. this would be much nicer if
182 # global (SVN-style) versioning were used - then that would be
184 elements.sort! do |a, b|
185 if (a.timestamp == b.timestamp)
186 a.version <=> b.version
188 a.timestamp <=> b.timestamp
192 # create an osmChange document for the output
193 result = OSM::API.new.get_xml_doc
194 result.root.name = "osmChange"
196 # generate an output element for each operation. note: we avoid looking
197 # at the history because it is simpler - but it would be more correct to
198 # check these assertions.
199 elements.each do |elt|
201 if (elt.version == 1)
202 # first version, so it must be newly-created.
203 created = XML::Node.new "create"
204 created << elt.to_xml_node
206 # get the previous version from the element history
207 prev_elt = elt.class.find(:first, :conditions =>
208 ['id = ? and version = ?',
209 elt.id, elt.version])
211 # if the element isn't visible then it must have been deleted, so
212 # output the *previous* XML
213 deleted = XML::Node.new "delete"
214 deleted << prev_elt.to_xml_node
216 # must be a modify, for which we don't need the previous version
218 modified = XML::Node.new "modify"
219 modified << elt.to_xml_node
224 render :text => result.to_s, :content_type => "text/xml"
226 rescue ActiveRecord::RecordNotFound
227 render :nothing => true, :status => :not_found
228 rescue OSM::APIError => ex
229 render ex.render_opts
233 # query changesets by bounding box, time, user or open/closed status.
235 # create the conditions that the user asked for. some or all of
237 conditions = conditions_bbox(params['bbox'])
238 conditions = cond_merge conditions, conditions_user(params['user'])
239 conditions = cond_merge conditions, conditions_time(params['time'])
240 conditions = cond_merge conditions, conditions_open(params['open'])
242 # create the results document
243 results = OSM::API.new.get_xml_doc
245 # add all matching changesets to the XML results document
247 :conditions => conditions,
249 :order => 'created_at desc').each do |cs|
250 results.root << cs.to_xml_node
253 render :text => results.to_s, :content_type => "text/xml"
255 rescue ActiveRecord::RecordNotFound
256 render :nothing => true, :status => :not_found
257 rescue OSM::APIError => ex
258 render ex.render_opts
262 # updates a changeset's tags. none of the changeset's attributes are
263 # user-modifiable, so they will be ignored.
265 # changesets are not (yet?) versioned, so we don't have to deal with
266 # history tables here. changesets are locked to a single user, however.
268 # after succesful update, returns the XML of the changeset.
270 # request *must* be a PUT.
272 render :nothing => true, :status => :method_not_allowed
276 changeset = Changeset.find(params[:id])
277 new_changeset = Changeset.from_xml(request.raw_post)
279 unless new_changeset.nil?
280 check_changeset_consistency(changeset, @user)
281 changeset.update_from(new_changeset, @user)
282 render :text => changeset.to_xml, :mime_type => "text/xml"
285 render :nothing => true, :status => :bad_request
288 rescue ActiveRecord::RecordNotFound
289 render :nothing => true, :status => :not_found
290 rescue OSM::APIError => ex
291 render ex.render_opts
295 # list edits belonging to a user
297 user = User.find(:first, :conditions => [ "visible = ? and display_name = ?", true, params[:display_name]])
298 @edit_pages, @edits = paginate(:changesets,
299 :include => [:user, :changeset_tags],
300 :conditions => ["changesets.user_id = ? AND min_lat IS NOT NULL", user.id],
301 :order => "changesets.created_at DESC",
305 @display_name = user.display_name
306 # FIXME needs rescues in here
310 #------------------------------------------------------------
311 # utility functions below.
312 #------------------------------------------------------------
315 # merge two conditions
320 return [ a_str + " and " + b_str ] + a + b
329 # if a bounding box was specified then parse it and do some sanity
330 # checks. this is mostly the same as the map call, but without the
332 def conditions_bbox(bbox)
334 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
335 bbox = sanitise_boundaries(bbox.split(/,/))
336 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
337 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
338 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
339 bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
346 # restrict changesets to those by a particular user
347 def conditions_user(user)
349 # user input checking, we don't have any UIDs < 1
350 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
352 u = User.find(user.to_i)
353 # should be able to get changesets of public users only, or
354 # our own changesets regardless of public-ness.
355 unless u.data_public?
356 # get optional user auth stuff so that users can see their own
357 # changesets if they're non-public
360 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
362 return ['user_id = ?', u.id]
369 # restrict changes to those during a particular time period
370 def conditions_time(time)
372 # if there is a range, i.e: comma separated, then the first is
373 # low, second is high - same as with bounding boxes.
374 if time.count(',') == 1
375 # check that we actually have 2 elements in the array
376 times = time.split(/,/)
377 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
379 from, to = times.collect { |t| DateTime.parse(t) }
380 return ['closed_at >= ? and created_at <= ?', from, to]
382 # if there is no comma, assume its a lower limit on time
383 return ['closed_at >= ?', DateTime.parse(time)]
388 # stupid DateTime seems to throw both of these for bad parsing, so
389 # we have to catch both and ensure the correct code path is taken.
390 rescue ArgumentError => ex
391 raise OSM::APIBadUserInput.new(ex.message.to_s)
392 rescue RuntimeError => ex
393 raise OSM::APIBadUserInput.new(ex.message.to_s)
397 # restrict changes to those which are open
399 # at the moment this code assumes we're only interested in open
400 # changesets and gives no facility to query closed changesets. this
401 # would be reasonably simple to implement if anyone actually wants
403 def conditions_open(open)
404 return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?',
405 DateTime.now, Changeset::MAX_ELEMENTS]