1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
7 session :off, :except => [:list, :list_user, :list_bbox]
8 before_filter :authorize_web, :only => [:list, :list_user, :list_bbox]
9 before_filter :set_locale, :only => [:list, :list_user, :list_bbox]
10 before_filter :authorize, :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/index.php/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
261 # @changesets = Changeset.find(:all, :order => "closed_at DESC", :conditions => ['closed_at < ?', DateTime.now], :limit=> 20)
264 #@edit_pages, @edits = paginate(:changesets,
265 # :include => [:user, :changeset_tags],
266 # :conditions => conditions,
267 # :order => "changesets.created_at DESC",
271 @edits = Changeset.find(:all,
272 :order => "changesets.created_at DESC",
273 :conditions => conditions,
279 # list edits (changesets) belonging to a user
281 user = User.find_by_display_name(params[:display_name], :conditions => {:visible => true})
284 @display_name = user.display_name
285 if not user.data_public? and @user != user
289 conditions = cond_merge conditions, ['user_id = ?', user.id]
290 conditions = cond_merge conditions, conditions_nonempty
291 @edit_pages, @edits = paginate(:changesets,
292 :include => [:user, :changeset_tags],
293 :conditions => conditions,
294 :order => "changesets.created_at DESC",
298 @not_found_user = params[:display_name]
299 render :template => 'user/no_such_user', :status => :not_found
304 # list changesets in a bbox
306 # support 'bbox' param or alternatively 'minlon', 'minlat' etc
308 bbox = params['bbox']
309 elsif params['minlon'] and params['minlat'] and params['maxlon'] and params['maxlat']
310 bbox = h(params['minlon']) + ',' + h(params['minlat']) + ',' + h(params['maxlon']) + ',' + h(params['maxlat'])
312 #TODO: fix bugs in location determination for history tab (and other tabs) then uncomment this redirect
313 #redirect_to :action => 'list'
315 # For now just render immediately, and skip the db
320 conditions = conditions_bbox(bbox);
321 conditions = cond_merge conditions, conditions_nonempty
323 @edit_pages, @edits = paginate(:changesets,
324 :include => [:user, :changeset_tags],
325 :conditions => conditions,
326 :order => "changesets.created_at DESC",
329 @bbox = sanitise_boundaries(bbox.split(/,/)) unless bbox==nil
333 #------------------------------------------------------------
334 # utility functions below.
335 #------------------------------------------------------------
338 # merge two conditions
343 return [ a_str + " AND " + b_str ] + a + b
352 # if a bounding box was specified then parse it and do some sanity
353 # checks. this is mostly the same as the map call, but without the
355 def conditions_bbox(bbox)
357 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
358 bbox = sanitise_boundaries(bbox.split(/,/))
359 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
360 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
361 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
362 bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
369 # restrict changesets to those by a particular user
370 def conditions_user(user)
372 # user input checking, we don't have any UIDs < 1
373 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
375 u = User.find(user.to_i)
376 # should be able to get changesets of public users only, or
377 # our own changesets regardless of public-ness.
378 unless u.data_public?
379 # get optional user auth stuff so that users can see their own
380 # changesets if they're non-public
383 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
385 return ['user_id = ?', u.id]
392 # restrict changes to those closed during a particular time period
393 def conditions_time(time)
395 # if there is a range, i.e: comma separated, then the first is
396 # low, second is high - same as with bounding boxes.
397 if time.count(',') == 1
398 # check that we actually have 2 elements in the array
399 times = time.split(/,/)
400 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
402 from, to = times.collect { |t| DateTime.parse(t) }
403 return ['closed_at >= ? and created_at <= ?', from, to]
405 # if there is no comma, assume its a lower limit on time
406 return ['closed_at >= ?', DateTime.parse(time)]
411 # stupid DateTime seems to throw both of these for bad parsing, so
412 # we have to catch both and ensure the correct code path is taken.
413 rescue ArgumentError => ex
414 raise OSM::APIBadUserInput.new(ex.message.to_s)
415 rescue RuntimeError => ex
416 raise OSM::APIBadUserInput.new(ex.message.to_s)
420 # return changesets which are open (haven't been closed yet)
421 # we do this by seeing if the 'closed at' time is in the future. Also if we've
422 # hit the maximum number of changes then it counts as no longer open.
423 # if parameter 'open' is nill then open and closed changsets are returned
424 def conditions_open(open)
425 return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?',
426 Time.now.getutc, Changeset::MAX_ELEMENTS]
430 # query changesets which are closed
431 # ('closed at' time has passed or changes limit is hit)
432 def conditions_closed(closed)
433 return closed.nil? ? nil : ['closed_at < ? and num_changes > ?',
434 Time.now.getutc, Changeset::MAX_ELEMENTS]
438 # eliminate empty changesets (where the bbox has not been set)
439 # this should be applied to all changeset list displays
440 def conditions_nonempty()
441 return ['min_lat IS NOT NULL']