1 # The ChangesetController is the RESTful interface to Changeset objects
3 class ChangesetsController < ApplicationController
7 skip_before_action :verify_authenticity_token, :except => [:index]
8 before_action :authorize_web, :only => [:index, :feed]
9 before_action :set_locale, :only => [:index, :feed]
10 before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
11 before_action :api_deny_access_handler, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe, :expand_bbox]
15 before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
16 before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
17 before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :index, :feed, :subscribe, :unsubscribe]
18 before_action(:only => [:index, :feed]) { |c| c.check_database_readable(true) }
19 around_action :api_call_handle_error, :except => [:index, :feed]
20 around_action :api_call_timeout, :except => [:index, :feed, :upload]
21 around_action :web_timeout, :only => [:index, :feed]
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
33 cs.user = current_user
36 # Subscribe user to changeset comments
37 cs.subscribers << current_user
39 render :plain => cs.id.to_s
43 # Return XML giving the basic info about the changeset. Does not
44 # return anything about the nodes, ways and relations in the changeset.
46 changeset = Changeset.find(params[:id])
48 render :xml => changeset.to_xml(params[:include_discussion].presence).to_s
52 # marks a changeset as closed. this may be called multiple times
53 # on the same changeset, so is idempotent.
57 changeset = Changeset.find(params[:id])
58 check_changeset_consistency(changeset, current_user)
60 # to close the changeset, we'll just set its closed_at time to
61 # now. this might not be enough if there are concurrency issues,
62 # but we'll have to wait and see.
63 changeset.set_closed_time_now
70 # insert a (set of) points into a changeset bounding box. this can only
71 # increase the size of the bounding box. this is a hint that clients can
72 # set either before uploading a large number of changes, or changes that
73 # the client (but not the server) knows will affect areas further away.
75 # only allow POST requests, because although this method is
76 # idempotent, there is no "document" to PUT really...
79 cs = Changeset.find(params[:id])
80 check_changeset_consistency(cs, current_user)
82 # keep an array of lons and lats
86 # the request is in pseudo-osm format... this is kind-of an
87 # abuse, maybe should change to some other format?
88 doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
89 doc.find("//osm/node").each do |n|
90 lon << n["lon"].to_f * GeoRecord::SCALE
91 lat << n["lat"].to_f * GeoRecord::SCALE
94 # add the existing bounding box to the lon-lat array
95 lon << cs.min_lon unless cs.min_lon.nil?
96 lat << cs.min_lat unless cs.min_lat.nil?
97 lon << cs.max_lon unless cs.max_lon.nil?
98 lat << cs.max_lat unless cs.max_lat.nil?
100 # collapse the arrays to minimum and maximum
106 # save the larger bounding box and return the changeset, which
107 # will include the bigger bounding box.
109 render :xml => cs.to_xml.to_s
113 # Upload a diff in a single transaction.
115 # This means that each change within the diff must succeed, i.e: that
116 # each version number mentioned is still current. Otherwise the entire
117 # transaction *must* be rolled back.
119 # Furthermore, each element in the diff can only reference the current
122 # Returns: a diffResult document, as described in
123 # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
125 # only allow POST requests, as the upload method is most definitely
126 # not idempotent, as several uploads with placeholder IDs will have
127 # different side-effects.
128 # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
131 changeset = Changeset.find(params[:id])
132 check_changeset_consistency(changeset, current_user)
134 diff_reader = DiffReader.new(request.raw_post, changeset)
135 Changeset.transaction do
136 result = diff_reader.commit
137 render :xml => result.to_s
142 # download the changeset as an osmChange document.
144 # to make it easier to revert diffs it would be better if the osmChange
145 # format were reversible, i.e: contained both old and new versions of
146 # modified elements. but it doesn't at the moment...
148 # this method cannot order the database changes fully (i.e: timestamp and
149 # version number may be too coarse) so the resulting diff may not apply
150 # to a different database. however since changesets are not atomic this
151 # behaviour cannot be guaranteed anyway and is the result of a design
154 changeset = Changeset.find(params[:id])
156 # get all the elements in the changeset which haven't been redacted
157 # and stick them in a big array.
158 elements = [changeset.old_nodes.unredacted,
159 changeset.old_ways.unredacted,
160 changeset.old_relations.unredacted].flatten
162 # sort the elements by timestamp and version number, as this is the
163 # almost sensible ordering available. this would be much nicer if
164 # global (SVN-style) versioning were used - then that would be
166 elements.sort! do |a, b|
167 if a.timestamp == b.timestamp
168 a.version <=> b.version
170 a.timestamp <=> b.timestamp
174 # create changeset and user caches
176 user_display_name_cache = {}
178 # create an osmChange document for the output
179 result = OSM::API.new.get_xml_doc
180 result.root.name = "osmChange"
182 # generate an output element for each operation. note: we avoid looking
183 # at the history because it is simpler - but it would be more correct to
184 # check these assertions.
185 elements.each do |elt|
188 # first version, so it must be newly-created.
189 created = XML::Node.new "create"
190 created << elt.to_xml_node(changeset_cache, user_display_name_cache)
193 modified = XML::Node.new "modify"
194 modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
196 # if the element isn't visible then it must have been deleted
197 deleted = XML::Node.new "delete"
198 deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
202 render :xml => result.to_s
206 # query changesets by bounding box, time, user or open/closed status.
208 # find any bounding box
209 bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
211 # create the conditions that the user asked for. some or all of
213 changesets = Changeset.all
214 changesets = conditions_bbox(changesets, bbox)
215 changesets = conditions_user(changesets, params["user"], params["display_name"])
216 changesets = conditions_time(changesets, params["time"])
217 changesets = conditions_open(changesets, params["open"])
218 changesets = conditions_closed(changesets, params["closed"])
219 changesets = conditions_ids(changesets, params["changesets"])
221 # sort and limit the changesets
222 changesets = changesets.order("created_at DESC").limit(100)
224 # preload users, tags and comments
225 changesets = changesets.preload(:user, :changeset_tags, :comments)
227 # create the results document
228 results = OSM::API.new.get_xml_doc
230 # add all matching changesets to the XML results document
231 changesets.order("created_at DESC").limit(100).each do |cs|
232 results.root << cs.to_xml_node
235 render :xml => results.to_s
239 # updates a changeset's tags. none of the changeset's attributes are
240 # user-modifiable, so they will be ignored.
242 # changesets are not (yet?) versioned, so we don't have to deal with
243 # history tables here. changesets are locked to a single user, however.
245 # after succesful update, returns the XML of the changeset.
247 # request *must* be a PUT.
250 changeset = Changeset.find(params[:id])
251 new_changeset = Changeset.from_xml(request.raw_post)
253 check_changeset_consistency(changeset, current_user)
254 changeset.update_from(new_changeset, current_user)
255 render :xml => changeset.to_xml.to_s
259 # list non-empty changesets in reverse chronological order
261 @params = params.permit(:display_name, :bbox, :friends, :nearby, :max_id, :list)
263 if request.format == :atom && @params[:max_id]
264 redirect_to url_for(@params.merge(:max_id => nil)), :status => :moved_permanently
268 if @params[:display_name]
269 user = User.find_by(:display_name => @params[:display_name])
270 if !user || !user.active?
271 render_unknown_user @params[:display_name]
276 if (@params[:friends] || @params[:nearby]) && !current_user
281 if request.format == :html && !@params[:list]
283 render :action => :history, :layout => map_layout
285 changesets = conditions_nonempty(Changeset.all)
287 if @params[:display_name]
288 changesets = if user.data_public? || user == current_user
289 changesets.where(:user_id => user.id)
291 changesets.where("false")
294 changesets = conditions_bbox(changesets, BoundingBox.from_bbox_params(params))
295 elsif @params[:friends] && current_user
296 changesets = changesets.where(:user_id => current_user.friend_users.identifiable)
297 elsif @params[:nearby] && current_user
298 changesets = changesets.where(:user_id => current_user.nearby)
301 changesets = changesets.where("changesets.id <= ?", @params[:max_id]) if @params[:max_id]
303 @edits = changesets.order("changesets.id DESC").limit(20).preload(:user, :changeset_tags, :comments)
305 render :action => :index, :layout => false
310 # list edits as an atom feed
316 # Adds a subscriber to the changeset
318 # Check the arguments are sane
319 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
321 # Extract the arguments
322 id = params[:id].to_i
324 # Find the changeset and check it is valid
325 changeset = Changeset.find(id)
326 raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
329 changeset.subscribers << current_user
331 # Return a copy of the updated changeset
332 render :xml => changeset.to_xml.to_s
336 # Removes a subscriber from the changeset
338 # Check the arguments are sane
339 raise OSM::APIBadUserInput, "No id was given" unless params[:id]
341 # Extract the arguments
342 id = params[:id].to_i
344 # Find the changeset and check it is valid
345 changeset = Changeset.find(id)
346 raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
348 # Remove the subscriber
349 changeset.subscribers.delete(current_user)
351 # Return a copy of the updated changeset
352 render :xml => changeset.to_xml.to_s
357 #------------------------------------------------------------
358 # utility functions below.
359 #------------------------------------------------------------
362 # if a bounding box was specified do some sanity checks.
363 # restrict changesets to those enclosed by a bounding box
364 # we need to return both the changesets and the bounding box
365 def conditions_bbox(changesets, bbox)
367 bbox.check_boundaries
368 bbox = bbox.to_scaled
370 changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
371 bbox.max_lon.to_i, bbox.min_lon.to_i,
372 bbox.max_lat.to_i, bbox.min_lat.to_i)
379 # restrict changesets to those by a particular user
380 def conditions_user(changesets, user, name)
381 if user.nil? && name.nil?
384 # shouldn't provide both name and UID
385 raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
387 # use either the name or the UID to find the user which we're selecting on.
389 # user input checking, we don't have any UIDs < 1
390 raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
392 u = User.find(user.to_i)
394 u = User.find_by(:display_name => name)
397 # make sure we found a user
398 raise OSM::APINotFoundError if u.nil?
400 # should be able to get changesets of public users only, or
401 # our own changesets regardless of public-ness.
402 unless u.data_public?
403 # get optional user auth stuff so that users can see their own
404 # changesets if they're non-public
407 raise OSM::APINotFoundError if current_user.nil? || current_user != u
410 changesets.where(:user_id => u.id)
415 # restrict changes to those closed during a particular time period
416 def conditions_time(changesets, time)
419 elsif time.count(",") == 1
420 # if there is a range, i.e: comma separated, then the first is
421 # low, second is high - same as with bounding boxes.
423 # check that we actually have 2 elements in the array
424 times = time.split(/,/)
425 raise OSM::APIBadUserInput, "bad time range" if times.size != 2
427 from, to = times.collect { |t| Time.parse(t) }
428 changesets.where("closed_at >= ? and created_at <= ?", from, to)
430 # if there is no comma, assume its a lower limit on time
431 changesets.where("closed_at >= ?", Time.parse(time))
433 # stupid Time seems to throw both of these for bad parsing, so
434 # we have to catch both and ensure the correct code path is taken.
435 rescue ArgumentError => ex
436 raise OSM::APIBadUserInput, ex.message.to_s
437 rescue RuntimeError => ex
438 raise OSM::APIBadUserInput, ex.message.to_s
442 # return changesets which are open (haven't been closed yet)
443 # we do this by seeing if the 'closed at' time is in the future. Also if we've
444 # hit the maximum number of changes then it counts as no longer open.
445 # if parameter 'open' is nill then open and closed changesets are returned
446 def conditions_open(changesets, open)
450 changesets.where("closed_at >= ? and num_changes <= ?",
451 Time.now.getutc, Changeset::MAX_ELEMENTS)
456 # query changesets which are closed
457 # ('closed at' time has passed or changes limit is hit)
458 def conditions_closed(changesets, closed)
462 changesets.where("closed_at < ? or num_changes > ?",
463 Time.now.getutc, Changeset::MAX_ELEMENTS)
468 # query changesets by a list of ids
469 # (either specified as array or comma-separated string)
470 def conditions_ids(changesets, ids)
474 raise OSM::APIBadUserInput, "No changesets were given to search for"
476 ids = ids.split(",").collect(&:to_i)
477 changesets.where(:id => ids)
482 # eliminate empty changesets (where the bbox has not been set)
483 # this should be applied to all changeset list displays
484 def conditions_nonempty(changesets)
485 changesets.where("num_changes > 0")