1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
7 before_filter :authorize_web, :only => [:list, :list_user, :list_bbox]
8 before_filter :set_locale, :only => [:list, :list_user, :list_bbox]
9 before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
10 before_filter :require_allow_write_api, :only => [:create, :update, :delete, :upload, :include, :close]
11 before_filter :require_public_data, :only => [:create, :update, :delete, :upload, :include, :close]
12 before_filter :check_api_writable, :only => [:create, :update, :delete, :upload, :include]
13 before_filter :check_api_readable, :except => [:create, :update, :delete, :upload, :download, :query]
14 after_filter :compress_output
15 around_filter :api_call_handle_error
17 filter_parameter_logging "<osmChange version"
19 # Help methods for checking boundary sanity and area size
22 # Helper methods for checking consistency
23 include ConsistencyValidations
25 # Create a changeset from XML.
29 cs = Changeset.from_xml(request.raw_post, true)
34 render :text => cs.id.to_s, :content_type => "text/plain"
36 raise OSM::APIBadXMLError.new(Changeset, request.raw_post);
41 # Return XML giving the basic info about the changeset. Does not
42 # return anything about the nodes, ways and relations in the changeset.
44 changeset = Changeset.find(params[:id])
45 render :text => changeset.to_xml.to_s, :content_type => "text/xml"
49 # marks a changeset as closed. this may be called multiple times
50 # on the same changeset, so is idempotent.
54 changeset = Changeset.find(params[:id])
55 check_changeset_consistency(changeset, @user)
57 # to close the changeset, we'll just set its closed_at time to
58 # now. this might not be enough if there are concurrency issues,
59 # but we'll have to wait and see.
60 changeset.set_closed_time_now
63 render :nothing => true
67 # insert a (set of) points into a changeset bounding box. this can only
68 # increase the size of the bounding box. this is a hint that clients can
69 # set either before uploading a large number of changes, or changes that
70 # the client (but not the server) knows will affect areas further away.
72 # only allow POST requests, because although this method is
73 # idempotent, there is no "document" to PUT really...
76 cs = Changeset.find(params[:id])
77 check_changeset_consistency(cs, @user)
79 # keep an array of lons and lats
83 # the request is in pseudo-osm format... this is kind-of an
84 # abuse, maybe should change to some other format?
85 doc = XML::Parser.string(request.raw_post).parse
86 doc.find("//osm/node").each do |n|
87 lon << n['lon'].to_f * GeoRecord::SCALE
88 lat << n['lat'].to_f * GeoRecord::SCALE
91 # add the existing bounding box to the lon-lat array
92 lon << cs.min_lon unless cs.min_lon.nil?
93 lat << cs.min_lat unless cs.min_lat.nil?
94 lon << cs.max_lon unless cs.max_lon.nil?
95 lat << cs.max_lat unless cs.max_lat.nil?
97 # collapse the arrays to minimum and maximum
98 cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
99 lon.min, lat.min, lon.max, lat.max
101 # save the larger bounding box and return the changeset, which
102 # will include the bigger bounding box.
104 render :text => cs.to_xml.to_s, :content_type => "text/xml"
108 # Upload a diff in a single transaction.
110 # This means that each change within the diff must succeed, i.e: that
111 # each version number mentioned is still current. Otherwise the entire
112 # transaction *must* be rolled back.
114 # Furthermore, each element in the diff can only reference the current
117 # Returns: a diffResult document, as described in
118 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
120 # only allow POST requests, as the upload method is most definitely
121 # not idempotent, as several uploads with placeholder IDs will have
122 # different side-effects.
123 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
126 changeset = Changeset.find(params[:id])
127 check_changeset_consistency(changeset, @user)
129 diff_reader = DiffReader.new(request.raw_post, changeset)
130 Changeset.transaction do
131 result = diff_reader.commit
132 render :text => result.to_s, :content_type => "text/xml"
137 # download the changeset as an osmChange document.
139 # to make it easier to revert diffs it would be better if the osmChange
140 # format were reversible, i.e: contained both old and new versions of
141 # modified elements. but it doesn't at the moment...
143 # this method cannot order the database changes fully (i.e: timestamp and
144 # version number may be too coarse) so the resulting diff may not apply
145 # to a different database. however since changesets are not atomic this
146 # behaviour cannot be guaranteed anyway and is the result of a design
149 changeset = Changeset.find(params[:id])
151 # get all the elements in the changeset and stick them in a big array.
152 elements = [changeset.old_nodes,
154 changeset.old_relations].flatten
156 # sort the elements by timestamp and version number, as this is the
157 # almost sensible ordering available. this would be much nicer if
158 # global (SVN-style) versioning were used - then that would be
160 elements.sort! do |a, b|
161 if (a.timestamp == b.timestamp)
162 a.version <=> b.version
164 a.timestamp <=> b.timestamp
168 # create an osmChange document for the output
169 result = OSM::API.new.get_xml_doc
170 result.root.name = "osmChange"
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|
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
182 # get the previous version from the element history
183 prev_elt = elt.class.find(:first, :conditions =>
184 ['id = ? and version = ?',
185 elt.id, elt.version])
187 # if the element isn't visible then it must have been deleted, so
188 # output the *previous* XML
189 deleted = XML::Node.new "delete"
190 deleted << prev_elt.to_xml_node
192 # must be a modify, for which we don't need the previous version
194 modified = XML::Node.new "modify"
195 modified << elt.to_xml_node
200 render :text => result.to_s, :content_type => "text/xml"
204 # query changesets by bounding box, time, user or open/closed status.
206 # create the conditions that the user asked for. some or all of
208 conditions = conditions_bbox(params['bbox'])
209 conditions = cond_merge conditions, conditions_user(params['user'])
210 conditions = cond_merge conditions, conditions_time(params['time'])
211 conditions = cond_merge conditions, conditions_open(params['open'])
212 conditions = cond_merge conditions, conditions_closed(params['closed'])
214 # create the results document
215 results = OSM::API.new.get_xml_doc
217 # add all matching changesets to the XML results document
219 :conditions => conditions,
221 :order => 'created_at desc').each do |cs|
222 results.root << cs.to_xml_node
225 render :text => results.to_s, :content_type => "text/xml"
229 # updates a changeset's tags. none of the changeset's attributes are
230 # user-modifiable, so they will be ignored.
232 # changesets are not (yet?) versioned, so we don't have to deal with
233 # history tables here. changesets are locked to a single user, however.
235 # after succesful update, returns the XML of the changeset.
237 # request *must* be a PUT.
240 changeset = Changeset.find(params[:id])
241 new_changeset = Changeset.from_xml(request.raw_post)
243 unless new_changeset.nil?
244 check_changeset_consistency(changeset, @user)
245 changeset.update_from(new_changeset, @user)
246 render :text => changeset.to_xml, :mime_type => "text/xml"
249 render :nothing => true, :status => :bad_request
256 # list edits (open changesets) in reverse chronological order
258 conditions = conditions_nonempty
260 if params[:display_name]
261 user = User.find_by_display_name(params[:display_name], :conditions => { :visible => true })
264 if user.data_public? or user == @user
265 conditions = cond_merge conditions, ['user_id = ?', user.id]
267 conditions = cond_merge conditions, ['false']
269 elsif request.format == :html
270 @title = t 'user.no_such_user.title'
271 @not_found_user = params[:display_name]
272 render :template => 'user/no_such_user', :status => :not_found
278 elsif params[:minlon] and params[:minlat] and params[:maxlon] and params[:maxlat]
279 bbox = params[:minlon] + ',' + params[:minlat] + ',' + params[:maxlon] + ',' + params[:maxlat]
283 conditions = cond_merge conditions, conditions_bbox(bbox)
284 bbox = BoundingBox.from_s(bbox)
285 bbox_link = "<a href='#{url_for(:controller => "site", :action => "index", :minlon => bbox.min_lon, :minlat => bbox.min_lat, :maxlon => bbox.max_lon, :maxlat => bbox.max_lat, :box => "yes")}'>#{bbox.to_s}</a>"
288 @title = t 'changeset.list.title'
291 @description = t 'changeset.list.description_user_bbox', :user => user.display_name, :bbox => bbox_link
293 @description = t 'changeset.list.description_user', :user => user.display_name
295 @description = t 'changeset.list.description_bbox', :bbox => bbox_link
297 @description = t 'changeset.list.description'
300 @edit_pages, @edits = paginate(:changesets,
301 :include => [:user, :changeset_tags],
302 :conditions => conditions,
303 :order => "changesets.created_at DESC",
308 #------------------------------------------------------------
309 # utility functions below.
310 #------------------------------------------------------------
313 # merge two conditions
318 return [ a_str + " AND " + b_str ] + a + b
327 # if a bounding box was specified then parse it and do some sanity
328 # checks. this is mostly the same as the map call, but without the
330 def conditions_bbox(bbox)
332 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
333 bbox = sanitise_boundaries(bbox.split(/,/))
334 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
335 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
336 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
337 bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
344 # restrict changesets to those by a particular user
345 def conditions_user(user)
347 # user input checking, we don't have any UIDs < 1
348 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
350 u = User.find(user.to_i)
351 # should be able to get changesets of public users only, or
352 # our own changesets regardless of public-ness.
353 unless u.data_public?
354 # get optional user auth stuff so that users can see their own
355 # changesets if they're non-public
358 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
360 return ['user_id = ?', u.id]
367 # restrict changes to those closed during a particular time period
368 def conditions_time(time)
370 # if there is a range, i.e: comma separated, then the first is
371 # low, second is high - same as with bounding boxes.
372 if time.count(',') == 1
373 # check that we actually have 2 elements in the array
374 times = time.split(/,/)
375 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
377 from, to = times.collect { |t| DateTime.parse(t) }
378 return ['closed_at >= ? and created_at <= ?', from, to]
380 # if there is no comma, assume its a lower limit on time
381 return ['closed_at >= ?', DateTime.parse(time)]
386 # stupid DateTime seems to throw both of these for bad parsing, so
387 # we have to catch both and ensure the correct code path is taken.
388 rescue ArgumentError => ex
389 raise OSM::APIBadUserInput.new(ex.message.to_s)
390 rescue RuntimeError => ex
391 raise OSM::APIBadUserInput.new(ex.message.to_s)
395 # return changesets which are open (haven't been closed yet)
396 # we do this by seeing if the 'closed at' time is in the future. Also if we've
397 # hit the maximum number of changes then it counts as no longer open.
398 # if parameter 'open' is nill then open and closed changsets are returned
399 def conditions_open(open)
400 return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?',
401 Time.now.getutc, Changeset::MAX_ELEMENTS]
405 # query changesets which are closed
406 # ('closed at' time has passed or changes limit is hit)
407 def conditions_closed(closed)
408 return closed.nil? ? nil : ['closed_at < ? and num_changes > ?',
409 Time.now.getutc, Changeset::MAX_ELEMENTS]
413 # eliminate empty changesets (where the bbox has not been set)
414 # this should be applied to all changeset list displays
415 def conditions_nonempty()
416 return ['min_lat IS NOT NULL']