1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetController < ApplicationController
7 skip_before_filter :verify_authenticity_token, :except => [:list]
8 before_filter :authorize_web, :only => [:list]
9 before_filter :set_locale, :only => [:list]
10 before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
11 before_filter :require_allow_write_api, :only => [:create, :update, :delete, :upload, :include, :close]
12 before_filter :require_public_data, :only => [:create, :update, :delete, :upload, :include, :close]
13 before_filter :check_api_writable, :only => [:create, :update, :delete, :upload, :include]
14 before_filter :check_api_readable, :except => [:create, :update, :delete, :upload, :download, :query, :list]
15 before_filter(:only => [:list]) { |c| c.check_database_readable(true) }
16 after_filter :compress_output
17 around_filter :api_call_handle_error, :except => [:list]
18 around_filter :web_timeout, :only => [:list]
20 # Help methods for checking boundary sanity and area size
23 # Helper methods for checking consistency
24 include ConsistencyValidations
26 # Create a changeset from XML.
30 cs = Changeset.from_xml(request.raw_post, true)
32 # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
35 render :text => cs.id.to_s, :content_type => "text/plain"
39 # Return XML giving the basic info about the changeset. Does not
40 # 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"
47 # marks a changeset as closed. this may be called multiple times
48 # on the same changeset, so is idempotent.
52 changeset = Changeset.find(params[:id])
53 check_changeset_consistency(changeset, @user)
55 # to close the changeset, we'll just set its closed_at time to
56 # now. this might not be enough if there are concurrency issues,
57 # but we'll have to wait and see.
58 changeset.set_closed_time_now
61 render :nothing => true
65 # insert a (set of) points into a changeset bounding box. this can only
66 # increase the size of the bounding box. this is a hint that clients can
67 # set either before uploading a large number of changes, or changes that
68 # the client (but not the server) knows will affect areas further away.
70 # only allow POST requests, because although this method is
71 # idempotent, there is no "document" to PUT really...
74 cs = Changeset.find(params[:id])
75 check_changeset_consistency(cs, @user)
77 # keep an array of lons and lats
81 # the request is in pseudo-osm format... this is kind-of an
82 # abuse, maybe should change to some other format?
83 doc = XML::Parser.string(request.raw_post).parse
84 doc.find("//osm/node").each do |n|
85 lon << n['lon'].to_f * GeoRecord::SCALE
86 lat << n['lat'].to_f * GeoRecord::SCALE
89 # add the existing bounding box to the lon-lat array
90 lon << cs.min_lon unless cs.min_lon.nil?
91 lat << cs.min_lat unless cs.min_lat.nil?
92 lon << cs.max_lon unless cs.max_lon.nil?
93 lat << cs.max_lat unless cs.max_lat.nil?
95 # collapse the arrays to minimum and maximum
96 cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat =
97 lon.min, lat.min, lon.max, lat.max
99 # save the larger bounding box and return the changeset, which
100 # will include the bigger bounding box.
102 render :text => cs.to_xml.to_s, :content_type => "text/xml"
106 # Upload a diff in a single transaction.
108 # This means that each change within the diff must succeed, i.e: that
109 # each version number mentioned is still current. Otherwise the entire
110 # transaction *must* be rolled back.
112 # Furthermore, each element in the diff can only reference the current
115 # Returns: a diffResult document, as described in
116 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
118 # only allow POST requests, as the upload method is most definitely
119 # not idempotent, as several uploads with placeholder IDs will have
120 # different side-effects.
121 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
124 changeset = Changeset.find(params[:id])
125 check_changeset_consistency(changeset, @user)
127 diff_reader = DiffReader.new(request.raw_post, changeset)
128 Changeset.transaction do
129 result = diff_reader.commit
130 render :text => result.to_s, :content_type => "text/xml"
135 # download the changeset as an osmChange document.
137 # to make it easier to revert diffs it would be better if the osmChange
138 # format were reversible, i.e: contained both old and new versions of
139 # modified elements. but it doesn't at the moment...
141 # this method cannot order the database changes fully (i.e: timestamp and
142 # version number may be too coarse) so the resulting diff may not apply
143 # to a different database. however since changesets are not atomic this
144 # behaviour cannot be guaranteed anyway and is the result of a design
147 changeset = Changeset.find(params[:id])
149 # get all the elements in the changeset and stick them in a big array.
150 elements = [changeset.old_nodes,
152 changeset.old_relations].flatten
154 # sort the elements by timestamp and version number, as this is the
155 # almost sensible ordering available. this would be much nicer if
156 # global (SVN-style) versioning were used - then that would be
158 elements.sort! do |a, b|
159 if (a.timestamp == b.timestamp)
160 a.version <=> b.version
162 a.timestamp <=> b.timestamp
166 # create an osmChange document for the output
167 result = OSM::API.new.get_xml_doc
168 result.root.name = "osmChange"
170 # generate an output element for each operation. note: we avoid looking
171 # at the history because it is simpler - but it would be more correct to
172 # check these assertions.
173 elements.each do |elt|
175 if (elt.version == 1)
176 # first version, so it must be newly-created.
177 created = XML::Node.new "create"
178 created << elt.to_xml_node
180 # get the previous version from the element history
181 prev_elt = elt.class.find([elt.id, elt.version])
183 # if the element isn't visible then it must have been deleted, so
184 # output the *previous* XML
185 deleted = XML::Node.new "delete"
186 deleted << prev_elt.to_xml_node
188 # must be a modify, for which we don't need the previous version
190 modified = XML::Node.new "modify"
191 modified << elt.to_xml_node
196 render :text => result.to_s, :content_type => "text/xml"
200 # query changesets by bounding box, time, user or open/closed status.
202 # create the conditions that the user asked for. some or all of
204 changesets = Changeset.scoped
205 changesets = conditions_bbox(changesets, params['bbox'])
206 changesets = conditions_user(changesets, params['user'], params['display_name'])
207 changesets = conditions_time(changesets, params['time'])
208 changesets = conditions_open(changesets, params['open'])
209 changesets = conditions_closed(changesets, params['closed'])
211 # create the results document
212 results = OSM::API.new.get_xml_doc
214 # add all matching changesets to the XML results document
215 changesets.order("created_at DESC").limit(100).each do |cs|
216 results.root << cs.to_xml_node
219 render :text => results.to_s, :content_type => "text/xml"
223 # updates a changeset's tags. none of the changeset's attributes are
224 # user-modifiable, so they will be ignored.
226 # changesets are not (yet?) versioned, so we don't have to deal with
227 # history tables here. changesets are locked to a single user, however.
229 # after succesful update, returns the XML of the changeset.
231 # request *must* be a PUT.
234 changeset = Changeset.find(params[:id])
235 new_changeset = Changeset.from_xml(request.raw_post)
237 unless new_changeset.nil?
238 check_changeset_consistency(changeset, @user)
239 changeset.update_from(new_changeset, @user)
240 render :text => changeset.to_xml, :mime_type => "text/xml"
243 render :nothing => true, :status => :bad_request
250 # list edits (open changesets) in reverse chronological order
252 if request.format == :atom and params[:page]
253 redirect_to params.merge({ :page => nil }), :status => :moved_permanently
255 changesets = conditions_nonempty(Changeset.scoped)
257 if params[:display_name]
258 user = User.find_by_display_name(params[:display_name])
260 if user and user.active?
261 if user.data_public? or user == @user
262 changesets = changesets.where(:user_id => user.id)
264 changesets = changesets.where("false")
266 elsif request.format == :html
267 @title = t 'user.no_such_user.title'
268 @not_found_user = params[:display_name]
269 render :template => 'user/no_such_user', :status => :not_found
275 elsif params[:minlon] and params[:minlat] and params[:maxlon] and params[:maxlat]
276 bbox = params[:minlon] + ',' + params[:minlat] + ',' + params[:maxlon] + ',' + params[:maxlat]
280 changesets = conditions_bbox(changesets, bbox)
281 bbox = BoundingBox.from_s(bbox)
282 bbox_link = render_to_string :partial => "bbox", :object => bbox
286 user_link = render_to_string :partial => "user", :object => user
290 @title = t 'changeset.list.title_user_bbox', :user => user.display_name, :bbox => bbox.to_s
291 @heading = t 'changeset.list.heading_user_bbox', :user => user.display_name, :bbox => bbox.to_s
292 @description = t 'changeset.list.description_user_bbox', :user => user_link, :bbox => bbox_link
294 @title = t 'changeset.list.title_user', :user => user.display_name
295 @heading = t 'changeset.list.heading_user', :user => user.display_name
296 @description = t 'changeset.list.description_user', :user => user_link
298 @title = t 'changeset.list.title_bbox', :bbox => bbox.to_s
299 @heading = t 'changeset.list.heading_bbox', :bbox => bbox.to_s
300 @description = t 'changeset.list.description_bbox', :bbox => bbox_link
302 @title = t 'changeset.list.title'
303 @heading = t 'changeset.list.heading'
304 @description = t 'changeset.list.description'
307 @page = (params[:page] || 1).to_i
312 @edits = changesets.order("changesets.created_at DESC").offset((@page - 1) * @page_size).limit(@page_size).preload(:user, :changeset_tags)
317 #------------------------------------------------------------
318 # utility functions below.
319 #------------------------------------------------------------
322 # if a bounding box was specified then parse it and do some sanity
323 # checks. this is mostly the same as the map call, but without the
325 def conditions_bbox(changesets, bbox)
327 raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
328 bbox = sanitise_boundaries(bbox.split(/,/))
329 raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
330 raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
331 return changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
332 (bbox[2] * GeoRecord::SCALE).to_i,
333 (bbox[0] * GeoRecord::SCALE).to_i,
334 (bbox[3] * GeoRecord::SCALE).to_i,
335 (bbox[1] * GeoRecord::SCALE).to_i)
342 # restrict changesets to those by a particular user
343 def conditions_user(changesets, user, name)
344 unless user.nil? and name.nil?
345 # shouldn't provide both name and UID
346 raise OSM::APIBadUserInput.new("provide either the user ID or display name, but not both") if user and name
348 # use either the name or the UID to find the user which we're selecting on.
350 # user input checking, we don't have any UIDs < 1
351 raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
352 u = User.find(user.to_i)
354 u = User.find_by_display_name(name)
357 # make sure we found a user
358 raise OSM::APINotFoundError.new if u.nil?
360 # should be able to get changesets of public users only, or
361 # our own changesets regardless of public-ness.
362 unless u.data_public?
363 # get optional user auth stuff so that users can see their own
364 # changesets if they're non-public
367 raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
369 return changesets.where(:user_id => u.id)
376 # restrict changes to those closed during a particular time period
377 def conditions_time(changesets, time)
379 # if there is a range, i.e: comma separated, then the first is
380 # low, second is high - same as with bounding boxes.
381 if time.count(',') == 1
382 # check that we actually have 2 elements in the array
383 times = time.split(/,/)
384 raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
386 from, to = times.collect { |t| DateTime.parse(t) }
387 return changesets.where("closed_at >= ? and created_at <= ?", from, to)
389 # if there is no comma, assume its a lower limit on time
390 return changesets.where("closed_at >= ?", DateTime.parse(time))
395 # stupid DateTime seems to throw both of these for bad parsing, so
396 # we have to catch both and ensure the correct code path is taken.
397 rescue ArgumentError => ex
398 raise OSM::APIBadUserInput.new(ex.message.to_s)
399 rescue RuntimeError => ex
400 raise OSM::APIBadUserInput.new(ex.message.to_s)
404 # return changesets which are open (haven't been closed yet)
405 # we do this by seeing if the 'closed at' time is in the future. Also if we've
406 # hit the maximum number of changes then it counts as no longer open.
407 # if parameter 'open' is nill then open and closed changesets are returned
408 def conditions_open(changesets, open)
412 return changesets.where("closed_at >= ? and num_changes <= ?",
413 Time.now.getutc, Changeset::MAX_ELEMENTS)
418 # query changesets which are closed
419 # ('closed at' time has passed or changes limit is hit)
420 def conditions_closed(changesets, closed)
424 return changesets.where("closed_at < ? or num_changes > ?",
425 Time.now.getutc, Changeset::MAX_ELEMENTS)
430 # eliminate empty changesets (where the bbox has not been set)
431 # this should be applied to all changeset list displays
432 def conditions_nonempty(changesets)
433 return changesets.where("num_changes > 0")