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 :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'])
241 conditions = cond_merge conditions, conditions_closed(params['closed'])
243 # create the results document
244 results = OSM::API.new.get_xml_doc
246 # add all matching changesets to the XML results document
248 :conditions => conditions,
250 :order => 'created_at desc').each do |cs|
251 results.root << cs.to_xml_node
254 render :text => results.to_s, :content_type => "text/xml"
256 rescue ActiveRecord::RecordNotFound
257 render :nothing => true, :status => :not_found
258 rescue OSM::APIError => ex
259 render ex.render_opts
263 # updates a changeset's tags. none of the changeset's attributes are
264 # user-modifiable, so they will be ignored.
266 # changesets are not (yet?) versioned, so we don't have to deal with
267 # history tables here. changesets are locked to a single user, however.
269 # after succesful update, returns the XML of the changeset.
271 # request *must* be a PUT.
273 render :nothing => true, :status => :method_not_allowed
277 changeset = Changeset.find(params[:id])
278 new_changeset = Changeset.from_xml(request.raw_post)
280 unless new_changeset.nil?
281 check_changeset_consistency(changeset, @user)
282 changeset.update_from(new_changeset, @user)
283 render :text => changeset.to_xml, :mime_type => "text/xml"
286 render :nothing => true, :status => :bad_request
289 rescue ActiveRecord::RecordNotFound
290 render :nothing => true, :status => :not_found
291 rescue OSM::APIError => ex
292 render ex.render_opts
298 # list edits (open changesets) in reverse chronological order
300 conditions = conditions_nonempty
303 # @changesets = Changeset.find(:all, :order => "closed_at DESC", :conditions => ['closed_at < ?', DateTime.now], :limit=> 20)
306 #@edit_pages, @edits = paginate(:changesets,
307 # :include => [:user, :changeset_tags],
308 # :conditions => conditions,
309 # :order => "changesets.created_at DESC",
313 @edits = Changeset.find(:all,
314 :order => "changesets.created_at DESC",
315 :conditions => conditions,
321 # list edits (changesets) belonging to a user
323 user = User.find_by_display_name(params[:display_name], :conditions => {:visible => true})
326 @display_name = user.display_name
327 if not user.data_public? and @user != user
331 conditions = cond_merge conditions, ['user_id = ?', user.id]
332 conditions = cond_merge conditions, conditions_nonempty
333 @edit_pages, @edits = paginate(:changesets,
334 :include => [:user, :changeset_tags],
335 :conditions => conditions,
336 :order => "changesets.created_at DESC",
340 @not_found_user = params[:display_name]
341 render :template => 'user/no_such_user', :status => :not_found
346 # list changesets in a bbox
348 # support 'bbox' param or alternatively 'minlon', 'minlat' etc
350 bbox = params['bbox']
351 elsif params['minlon'] and params['minlat'] and params['maxlon'] and params['maxlat']
352 bbox = h(params['minlon']) + ',' + h(params['minlat']) + ',' + h(params['maxlon']) + ',' + h(params['maxlat'])
354 #TODO: fix bugs in location determination for history tab (and other tabs) then uncomment this redirect
355 #redirect_to :action => 'list'
358 conditions = conditions_bbox(bbox);
359 conditions = cond_merge conditions, conditions_nonempty
361 @edit_pages, @edits = paginate(:changesets,
362 :include => [:user, :changeset_tags],
363 :conditions => conditions,
364 :order => "changesets.created_at DESC",
367 @bbox = sanitise_boundaries(bbox.split(/,/)) unless bbox==nil
371 #------------------------------------------------------------
372 # utility functions below.
373 #------------------------------------------------------------
376 # merge two conditions
381 return [ a_str + " AND " + b_str ] + a + b
390 # if a bounding box was specified then parse it and do some sanity
391 # checks. this is mostly the same as the map call, but without the
393 def conditions_bbox(bbox)
395 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
396 bbox = sanitise_boundaries(bbox.split(/,/))
397 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
398 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
399 return ['min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?',
400 bbox[2] * GeoRecord::SCALE, bbox[0] * GeoRecord::SCALE, bbox[3]* GeoRecord::SCALE, bbox[1] * GeoRecord::SCALE]
407 # restrict changesets to those by a particular user
408 def conditions_user(user)
410 # user input checking, we don't have any UIDs < 1
411 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
413 u = User.find(user.to_i)
414 # should be able to get changesets of public users only, or
415 # our own changesets regardless of public-ness.
416 unless u.data_public?
417 # get optional user auth stuff so that users can see their own
418 # changesets if they're non-public
421 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
423 return ['user_id = ?', u.id]
430 # restrict changes to those closed during a particular time period
431 def conditions_time(time)
433 # if there is a range, i.e: comma separated, then the first is
434 # low, second is high - same as with bounding boxes.
435 if time.count(',') == 1
436 # check that we actually have 2 elements in the array
437 times = time.split(/,/)
438 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
440 from, to = times.collect { |t| DateTime.parse(t) }
441 return ['closed_at >= ? and created_at <= ?', from, to]
443 # if there is no comma, assume its a lower limit on time
444 return ['closed_at >= ?', DateTime.parse(time)]
449 # stupid DateTime seems to throw both of these for bad parsing, so
450 # we have to catch both and ensure the correct code path is taken.
451 rescue ArgumentError => ex
452 raise OSM::APIBadUserInput.new(ex.message.to_s)
453 rescue RuntimeError => ex
454 raise OSM::APIBadUserInput.new(ex.message.to_s)
458 # return changesets which are open (haven't been closed yet)
459 # we do this by seeing if the 'closed at' time is in the future. Also if we've
460 # hit the maximum number of changes then it counts as no longer open.
461 # if parameter 'open' is nill then open and closed changsets are returned
462 def conditions_open(open)
463 return open.nil? ? nil : ['closed_at >= ? and num_changes <= ?',
464 DateTime.now, Changeset::MAX_ELEMENTS]
468 # query changesets which are closed
469 # ('closed at' time has passed or changes limit is hit)
470 def conditions_closed(closed)
471 return closed.nil? ? nil : ['closed_at < ? and num_changes > ?',
472 DateTime.now, Changeset::MAX_ELEMENTS]
476 # eliminate empty changesets (where the bbox has not been set)
477 # this should be applied to all changeset list displays
478 def conditions_nonempty()
479 return ['min_lat IS NOT NULL']