1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
7 before_filter :authorize_web, :only => [:list]
8 before_filter :set_locale, :only => [:list]
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, :list]
14 before_filter(:only => [:list]) { |c| c.check_database_readable(true) }
15 after_filter :compress_output
16 around_filter :api_call_handle_error, :except => [:list]
17 around_filter :web_timeout, :only => [:list]
19 filter_parameter_logging "<osmChange version"
21 # Help methods for checking boundary sanity and area size
24 # Helper methods for checking consistency
25 include ConsistencyValidations
27 # Create a changeset from XML.
31 cs = Changeset.from_xml(request.raw_post, true)
33 # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
36 render :text => cs.id.to_s, :content_type => "text/plain"
40 # Return XML giving the basic info about the changeset. Does not
41 # return anything about the nodes, ways and relations in the changeset.
43 changeset = Changeset.find(params[:id])
44 render :text => changeset.to_xml.to_s, :content_type => "text/xml"
48 # marks a changeset as closed. this may be called multiple times
49 # on the same changeset, so is idempotent.
53 changeset = Changeset.find(params[:id])
54 check_changeset_consistency(changeset, @user)
56 # to close the changeset, we'll just set its closed_at time to
57 # now. this might not be enough if there are concurrency issues,
58 # but we'll have to wait and see.
59 changeset.set_closed_time_now
62 render :nothing => true
66 # insert a (set of) points into a changeset bounding box. this can only
67 # increase the size of the bounding box. this is a hint that clients can
68 # set either before uploading a large number of changes, or changes that
69 # the client (but not the server) knows will affect areas further away.
71 # only allow POST requests, because although this method is
72 # idempotent, there is no "document" to PUT really...
75 cs = Changeset.find(params[:id])
76 check_changeset_consistency(cs, @user)
78 # keep an array of lons and lats
82 # the request is in pseudo-osm format... this is kind-of an
83 # abuse, maybe should change to some other format?
84 doc = XML::Parser.string(request.raw_post).parse
85 doc.find("//osm/node").each do |n|
86 lon << n['lon'].to_f * GeoRecord::SCALE
87 lat << n['lat'].to_f * GeoRecord::SCALE
90 # add the existing bounding box to the lon-lat array
91 lon << cs.min_lon unless cs.min_lon.nil?
92 lat << cs.min_lat unless cs.min_lat.nil?
93 lon << cs.max_lon unless cs.max_lon.nil?
94 lat << cs.max_lat unless cs.max_lat.nil?
96 # collapse the arrays to minimum and maximum
97 cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
98 lon.min, lat.min, lon.max, lat.max
100 # save the larger bounding box and return the changeset, which
101 # will include the bigger bounding box.
103 render :text => cs.to_xml.to_s, :content_type => "text/xml"
107 # Upload a diff in a single transaction.
109 # This means that each change within the diff must succeed, i.e: that
110 # each version number mentioned is still current. Otherwise the entire
111 # transaction *must* be rolled back.
113 # Furthermore, each element in the diff can only reference the current
116 # Returns: a diffResult document, as described in
117 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
119 # only allow POST requests, as the upload method is most definitely
120 # not idempotent, as several uploads with placeholder IDs will have
121 # different side-effects.
122 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
125 changeset = Changeset.find(params[:id])
126 check_changeset_consistency(changeset, @user)
128 diff_reader = DiffReader.new(request.raw_post, changeset)
129 Changeset.transaction do
130 result = diff_reader.commit
131 render :text => result.to_s, :content_type => "text/xml"
136 # download the changeset as an osmChange document.
138 # to make it easier to revert diffs it would be better if the osmChange
139 # format were reversible, i.e: contained both old and new versions of
140 # modified elements. but it doesn't at the moment...
142 # this method cannot order the database changes fully (i.e: timestamp and
143 # version number may be too coarse) so the resulting diff may not apply
144 # to a different database. however since changesets are not atomic this
145 # behaviour cannot be guaranteed anyway and is the result of a design
148 changeset = Changeset.find(params[:id])
150 # get all the elements in the changeset and stick them in a big array.
151 elements = [changeset.old_nodes,
153 changeset.old_relations].flatten
155 # sort the elements by timestamp and version number, as this is the
156 # almost sensible ordering available. this would be much nicer if
157 # global (SVN-style) versioning were used - then that would be
159 elements.sort! do |a, b|
160 if (a.timestamp == b.timestamp)
161 a.version <=> b.version
163 a.timestamp <=> b.timestamp
167 # create an osmChange document for the output
168 result = OSM::API.new.get_xml_doc
169 result.root.name = "osmChange"
171 # generate an output element for each operation. note: we avoid looking
172 # at the history because it is simpler - but it would be more correct to
173 # check these assertions.
174 elements.each do |elt|
176 if (elt.version == 1)
177 # first version, so it must be newly-created.
178 created = XML::Node.new "create"
179 created << elt.to_xml_node
181 # get the previous version from the element history
182 prev_elt = elt.class.find(:first, :conditions =>
183 ['id = ? and version = ?',
184 elt.id, elt.version])
186 # if the element isn't visible then it must have been deleted, so
187 # output the *previous* XML
188 deleted = XML::Node.new "delete"
189 deleted << prev_elt.to_xml_node
191 # must be a modify, for which we don't need the previous version
193 modified = XML::Node.new "modify"
194 modified << elt.to_xml_node
199 render :text => result.to_s, :content_type => "text/xml"
203 # query changesets by bounding box, time, user or open/closed status.
205 # create the conditions that the user asked for. some or all of
207 conditions = conditions_bbox(params['bbox'])
208 conditions = cond_merge conditions, conditions_user(params['user'], params['display_name'])
209 conditions = cond_merge conditions, conditions_time(params['time'])
210 conditions = cond_merge conditions, conditions_open(params['open'])
211 conditions = cond_merge conditions, conditions_closed(params['closed'])
213 # create the results document
214 results = OSM::API.new.get_xml_doc
216 # add all matching changesets to the XML results document
218 :conditions => conditions,
220 :order => 'created_at desc').each do |cs|
221 results.root << cs.to_xml_node
224 render :text => results.to_s, :content_type => "text/xml"
228 # updates a changeset's tags. none of the changeset's attributes are
229 # user-modifiable, so they will be ignored.
231 # changesets are not (yet?) versioned, so we don't have to deal with
232 # history tables here. changesets are locked to a single user, however.
234 # after succesful update, returns the XML of the changeset.
236 # request *must* be a PUT.
239 changeset = Changeset.find(params[:id])
240 new_changeset = Changeset.from_xml(request.raw_post)
242 unless new_changeset.nil?
243 check_changeset_consistency(changeset, @user)
244 changeset.update_from(new_changeset, @user)
245 render :text => changeset.to_xml, :mime_type => "text/xml"
248 render :nothing => true, :status => :bad_request
255 # list edits (open changesets) in reverse chronological order
257 conditions = conditions_nonempty
259 if params[:display_name]
260 user = User.find_by_display_name(params[:display_name], :conditions => { :status => ["active", "confirmed"] })
263 if user.data_public? or user == @user
264 conditions = cond_merge conditions, ['user_id = ?', user.id]
266 conditions = cond_merge conditions, ['false']
268 elsif request.format == :html
269 @title = t 'user.no_such_user.title'
270 @not_found_user = params[:display_name]
271 render :template => 'user/no_such_user', :status => :not_found
277 elsif params[:minlon] and params[:minlat] and params[:maxlon] and params[:maxlat]
278 bbox = params[:minlon] + ',' + params[:minlat] + ',' + params[:maxlon] + ',' + params[:maxlat]
282 conditions = cond_merge conditions, conditions_bbox(bbox)
283 bbox = BoundingBox.from_s(bbox)
284 bbox_link = render_to_string :partial => "bbox", :object => bbox
288 user_link = render_to_string :partial => "user", :object => user
292 @title = t 'changeset.list.title_user_bbox', :user => user.display_name, :bbox => bbox.to_s
293 @heading = t 'changeset.list.heading_user_bbox', :user => user.display_name, :bbox => bbox.to_s
294 @description = t 'changeset.list.description_user_bbox', :user => user_link, :bbox => bbox_link
296 @title = t 'changeset.list.title_user', :user => user.display_name
297 @heading = t 'changeset.list.heading_user', :user => user.display_name
298 @description = t 'changeset.list.description_user', :user => user_link
300 @title = t 'changeset.list.title_bbox', :bbox => bbox.to_s
301 @heading = t 'changeset.list.heading_bbox', :bbox => bbox.to_s
302 @description = t 'changeset.list.description_bbox', :bbox => bbox_link
304 @title = t 'changeset.list.title'
305 @heading = t 'changeset.list.heading'
306 @description = t 'changeset.list.description'
309 @page = (params[:page] || 1).to_i
312 @edits = Changeset.find(:all,
313 :include => [:user, :changeset_tags],
314 :conditions => conditions,
315 :order => "changesets.created_at DESC",
316 :offset => (@page - 1) * @page_size,
317 :limit => @page_size)
321 #------------------------------------------------------------
322 # utility functions below.
323 #------------------------------------------------------------
326 # merge two conditions
331 return [ a_str + " AND " + b_str ] + a + b
340 # if a bounding box was specified then parse it and do some sanity
341 # checks. this is mostly the same as the map call, but without the
343 def conditions_bbox(bbox)
345 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
346 bbox = sanitise_boundaries(bbox.split(/,/))
347 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
348 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
349 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
350 (bbox[2] * GeoRecord::SCALE).to_i,
351 (bbox[0] * GeoRecord::SCALE).to_i,
352 (bbox[3] * GeoRecord::SCALE).to_i,
353 (bbox[1] * GeoRecord::SCALE).to_i]
360 # restrict changesets to those by a particular user
361 def conditions_user(user, name)
362 unless user.nil? and name.nil?
363 # shouldn't provide both name and UID
364 raise OSM::APIBadUserInput.new("provide either the user ID or display name, but not both") if user and name
366 # use either the name or the UID to find the user which we're selecting on.
368 # user input checking, we don't have any UIDs < 1
369 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
370 u = User.find(user.to_i)
372 u = User.find_by_display_name(name)
375 # make sure we found a user
376 raise OSM::APINotFoundError.new if u.nil?
378 # should be able to get changesets of public users only, or
379 # our own changesets regardless of public-ness.
380 unless u.data_public?
381 # get optional user auth stuff so that users can see their own
382 # changesets if they're non-public
385 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
387 return ['user_id = ?', u.id]
394 # restrict changes to those closed during a particular time period
395 def conditions_time(time)
397 # if there is a range, i.e: comma separated, then the first is
398 # low, second is high - same as with bounding boxes.
399 if time.count(',') == 1
400 # check that we actually have 2 elements in the array
401 times = time.split(/,/)
402 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
404 from, to = times.collect { |t| DateTime.parse(t) }
405 return ['closed_at >= ? and created_at <= ?', from, to]
407 # if there is no comma, assume its a lower limit on time
408 return ['closed_at >= ?', DateTime.parse(time)]
413 # stupid DateTime seems to throw both of these for bad parsing, so
414 # we have to catch both and ensure the correct code path is taken.
415 rescue ArgumentError => ex
416 raise OSM::APIBadUserInput.new(ex.message.to_s)
417 rescue RuntimeError => ex
418 raise OSM::APIBadUserInput.new(ex.message.to_s)
422 # return changesets which are open (haven't been closed yet)
423 # we do this by seeing if the 'closed at' time is in the future. Also if we've
424 # hit the maximum number of changes then it counts as no longer open.
425 # if parameter 'open' is nill then open and closed changsets are returned
426 def conditions_open(open)
427 return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?',
428 Time.now.getutc, Changeset::MAX_ELEMENTS]
432 # query changesets which are closed
433 # ('closed at' time has passed or changes limit is hit)
434 def conditions_closed(closed)
435 return closed.nil? ? nil : ['closed_at < ? or num_changes > ?',
436 Time.now.getutc, Changeset::MAX_ELEMENTS]
440 # eliminate empty changesets (where the bbox has not been set)
441 # this should be applied to all changeset list displays
442 def conditions_nonempty()
443 return ['min_lat IS NOT NULL']