]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/changesets_controller.rb
Show hidden comments to moderators if requested
[rails.git] / app / controllers / api / changesets_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 module Api
4   class ChangesetsController < ApiController
5     require "xml/libxml"
6
7     before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
8     before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :subscribe, :unsubscribe]
9     before_action :setup_user_auth, :only => [:show]
10     before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
11
12     authorize_resource
13
14     before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
15     before_action :set_request_formats, :except => [:create, :close, :upload]
16
17     around_action :api_call_handle_error
18     around_action :api_call_timeout, :except => [:upload]
19
20     # Helper methods for checking consistency
21     include ConsistencyValidations
22
23     ##
24     # Return XML giving the basic info about the changeset. Does not
25     # return anything about the nodes, ways and relations in the changeset.
26     def show
27       @changeset = Changeset.find(params[:id])
28       if params[:include_discussion].presence
29         @comments = @changeset.comments
30         @comments = @comments.unscope(:where => :visible) if params[:show_hidden_comments].presence && can?(:restore, ChangesetComment)
31         @comments = @comments.includes(:author)
32       end
33       render "changeset"
34
35       respond_to do |format|
36         format.xml
37         format.json
38       end
39     end
40
41     # Create a changeset from XML.
42     def create
43       assert_method :put
44
45       cs = Changeset.from_xml(request.raw_post, :create => true)
46
47       # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
48       cs.user = current_user
49       cs.save_with_tags!
50
51       # Subscribe user to changeset comments
52       cs.subscribers << current_user
53
54       render :plain => cs.id.to_s
55     end
56
57     ##
58     # marks a changeset as closed. this may be called multiple times
59     # on the same changeset, so is idempotent.
60     def close
61       assert_method :put
62
63       changeset = Changeset.find(params[:id])
64       check_changeset_consistency(changeset, current_user)
65
66       # to close the changeset, we'll just set its closed_at time to
67       # now. this might not be enough if there are concurrency issues,
68       # but we'll have to wait and see.
69       changeset.set_closed_time_now
70
71       changeset.save!
72       head :ok
73     end
74
75     ##
76     # Upload a diff in a single transaction.
77     #
78     # This means that each change within the diff must succeed, i.e: that
79     # each version number mentioned is still current. Otherwise the entire
80     # transaction *must* be rolled back.
81     #
82     # Furthermore, each element in the diff can only reference the current
83     # changeset.
84     #
85     # Returns: a diffResult document, as described in
86     # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
87     def upload
88       # only allow POST requests, as the upload method is most definitely
89       # not idempotent, as several uploads with placeholder IDs will have
90       # different side-effects.
91       # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
92       assert_method :post
93
94       changeset = Changeset.find(params[:id])
95       check_changeset_consistency(changeset, current_user)
96
97       diff_reader = DiffReader.new(request.raw_post, changeset)
98       Changeset.transaction do
99         result = diff_reader.commit
100         render :xml => result.to_s
101       end
102     end
103
104     ##
105     # download the changeset as an osmChange document.
106     #
107     # to make it easier to revert diffs it would be better if the osmChange
108     # format were reversible, i.e: contained both old and new versions of
109     # modified elements. but it doesn't at the moment...
110     #
111     # this method cannot order the database changes fully (i.e: timestamp and
112     # version number may be too coarse) so the resulting diff may not apply
113     # to a different database. however since changesets are not atomic this
114     # behaviour cannot be guaranteed anyway and is the result of a design
115     # choice.
116     def download
117       changeset = Changeset.find(params[:id])
118
119       # get all the elements in the changeset which haven't been redacted
120       # and stick them in a big array.
121       elements = [changeset.old_nodes.unredacted,
122                   changeset.old_ways.unredacted,
123                   changeset.old_relations.unredacted].flatten
124
125       # sort the elements by timestamp and version number, as this is the
126       # almost sensible ordering available. this would be much nicer if
127       # global (SVN-style) versioning were used - then that would be
128       # unambiguous.
129       elements.sort! do |a, b|
130         if a.timestamp == b.timestamp
131           a.version <=> b.version
132         else
133           a.timestamp <=> b.timestamp
134         end
135       end
136
137       # generate an output element for each operation. note: we avoid looking
138       # at the history because it is simpler - but it would be more correct to
139       # check these assertions.
140       @created = []
141       @modified = []
142       @deleted = []
143
144       elements.each do |elt|
145         if elt.version == 1
146           # first version, so it must be newly-created.
147           @created << elt
148         elsif elt.visible
149           # must be a modify
150           @modified << elt
151         else
152           # if the element isn't visible then it must have been deleted
153           @deleted << elt
154         end
155       end
156
157       respond_to do |format|
158         format.xml
159       end
160     end
161
162     ##
163     # query changesets by bounding box, time, user or open/closed status.
164     def query
165       raise OSM::APIBadUserInput, "cannot use order=oldest with time" if params[:time] && params[:order] == "oldest"
166
167       # find any bounding box
168       bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
169
170       # create the conditions that the user asked for. some or all of
171       # these may be nil.
172       changesets = Changeset.all
173       changesets = conditions_bbox(changesets, bbox)
174       changesets = conditions_user(changesets, params["user"], params["display_name"])
175       changesets = conditions_time(changesets, params["time"])
176       changesets = conditions_from_to(changesets, params["from"], params["to"])
177       changesets = conditions_open(changesets, params["open"])
178       changesets = conditions_closed(changesets, params["closed"])
179       changesets = conditions_ids(changesets, params["changesets"])
180
181       # sort the changesets
182       changesets = if params[:order] == "oldest"
183                      changesets.order(:created_at => :asc)
184                    else
185                      changesets.order(:created_at => :desc)
186                    end
187
188       # limit the result
189       changesets = changesets.limit(result_limit)
190
191       # preload users, tags and comments, and render result
192       @changesets = changesets.preload(:user, :changeset_tags, :comments)
193       render "changesets"
194
195       respond_to do |format|
196         format.xml
197         format.json
198       end
199     end
200
201     ##
202     # updates a changeset's tags. none of the changeset's attributes are
203     # user-modifiable, so they will be ignored.
204     #
205     # changesets are not (yet?) versioned, so we don't have to deal with
206     # history tables here. changesets are locked to a single user, however.
207     #
208     # after succesful update, returns the XML of the changeset.
209     def update
210       # request *must* be a PUT.
211       assert_method :put
212
213       @changeset = Changeset.find(params[:id])
214       new_changeset = Changeset.from_xml(request.raw_post)
215
216       check_changeset_consistency(@changeset, current_user)
217       @changeset.update_from(new_changeset, current_user)
218       render "changeset"
219
220       respond_to do |format|
221         format.xml
222         format.json
223       end
224     end
225
226     ##
227     # Adds a subscriber to the changeset
228     def subscribe
229       # Check the arguments are sane
230       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
231
232       # Extract the arguments
233       id = params[:id].to_i
234
235       # Find the changeset and check it is valid
236       changeset = Changeset.find(id)
237       raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
238
239       # Add the subscriber
240       changeset.subscribers << current_user
241
242       # Return a copy of the updated changeset
243       @changeset = changeset
244       render "changeset"
245
246       respond_to do |format|
247         format.xml
248         format.json
249       end
250     end
251
252     ##
253     # Removes a subscriber from the changeset
254     def unsubscribe
255       # Check the arguments are sane
256       raise OSM::APIBadUserInput, "No id was given" unless params[:id]
257
258       # Extract the arguments
259       id = params[:id].to_i
260
261       # Find the changeset and check it is valid
262       changeset = Changeset.find(id)
263       raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
264
265       # Remove the subscriber
266       changeset.subscribers.delete(current_user)
267
268       # Return a copy of the updated changeset
269       @changeset = changeset
270       render "changeset"
271
272       respond_to do |format|
273         format.xml
274         format.json
275       end
276     end
277
278     private
279
280     #------------------------------------------------------------
281     # utility functions below.
282     #------------------------------------------------------------
283
284     ##
285     # if a bounding box was specified do some sanity checks.
286     # restrict changesets to those enclosed by a bounding box
287     # we need to return both the changesets and the bounding box
288     def conditions_bbox(changesets, bbox)
289       if bbox
290         bbox.check_boundaries
291         bbox = bbox.to_scaled
292
293         changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
294                          bbox.max_lon.to_i, bbox.min_lon.to_i,
295                          bbox.max_lat.to_i, bbox.min_lat.to_i)
296       else
297         changesets
298       end
299     end
300
301     ##
302     # restrict changesets to those by a particular user
303     def conditions_user(changesets, user, name)
304       if user.nil? && name.nil?
305         changesets
306       else
307         # shouldn't provide both name and UID
308         raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
309
310         # use either the name or the UID to find the user which we're selecting on.
311         u = if name.nil?
312               # user input checking, we don't have any UIDs < 1
313               raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
314
315               u = User.find_by(:id => user.to_i)
316             else
317               u = User.find_by(:display_name => name)
318             end
319
320         # make sure we found a user
321         raise OSM::APINotFoundError if u.nil?
322
323         # should be able to get changesets of public users only, or
324         # our own changesets regardless of public-ness.
325         unless u.data_public?
326           # get optional user auth stuff so that users can see their own
327           # changesets if they're non-public
328           setup_user_auth
329
330           raise OSM::APINotFoundError if current_user.nil? || current_user != u
331         end
332
333         changesets.where(:user => u)
334       end
335     end
336
337     ##
338     # restrict changesets to those during a particular time period
339     def conditions_time(changesets, time)
340       if time.nil?
341         changesets
342       elsif time.count(",") == 1
343         # if there is a range, i.e: comma separated, then the first is
344         # low, second is high - same as with bounding boxes.
345
346         # check that we actually have 2 elements in the array
347         times = time.split(",")
348         raise OSM::APIBadUserInput, "bad time range" if times.size != 2
349
350         from, to = times.collect { |t| Time.parse(t).utc }
351         changesets.where("closed_at >= ? and created_at <= ?", from, to)
352       else
353         # if there is no comma, assume its a lower limit on time
354         changesets.where("closed_at >= ?", Time.parse(time).utc)
355       end
356       # stupid Time seems to throw both of these for bad parsing, so
357       # we have to catch both and ensure the correct code path is taken.
358     rescue ArgumentError, RuntimeError => e
359       raise OSM::APIBadUserInput, e.message.to_s
360     end
361
362     ##
363     # restrict changesets to those opened during a particular time period
364     # works similar to from..to of notes controller, including the requirement of 'from' when specifying 'to'
365     def conditions_from_to(changesets, from, to)
366       if from
367         begin
368           from = Time.parse(from).utc
369         rescue ArgumentError
370           raise OSM::APIBadUserInput, "Date #{from} is in a wrong format"
371         end
372
373         begin
374           to = if to
375                  Time.parse(to).utc
376                else
377                  Time.now.utc
378                end
379         rescue ArgumentError
380           raise OSM::APIBadUserInput, "Date #{to} is in a wrong format"
381         end
382
383         changesets.where(:created_at => from..to)
384       else
385         changesets
386       end
387     end
388
389     ##
390     # return changesets which are open (haven't been closed yet)
391     # we do this by seeing if the 'closed at' time is in the future. Also if we've
392     # hit the maximum number of changes then it counts as no longer open.
393     # if parameter 'open' is nill then open and closed changesets are returned
394     def conditions_open(changesets, open)
395       if open.nil?
396         changesets
397       else
398         changesets.where("closed_at >= ? and num_changes <= ?",
399                          Time.now.utc, Changeset::MAX_ELEMENTS)
400       end
401     end
402
403     ##
404     # query changesets which are closed
405     # ('closed at' time has passed or changes limit is hit)
406     def conditions_closed(changesets, closed)
407       if closed.nil?
408         changesets
409       else
410         changesets.where("closed_at < ? or num_changes > ?",
411                          Time.now.utc, Changeset::MAX_ELEMENTS)
412       end
413     end
414
415     ##
416     # query changesets by a list of ids
417     # (either specified as array or comma-separated string)
418     def conditions_ids(changesets, ids)
419       if ids.nil?
420         changesets
421       elsif ids.empty?
422         raise OSM::APIBadUserInput, "No changesets were given to search for"
423       else
424         ids = ids.split(",").collect(&:to_i)
425         changesets.where(:id => ids)
426       end
427     end
428
429     ##
430     # Get the maximum number of results to return
431     def result_limit
432       if params[:limit]
433         if params[:limit].to_i.positive? && params[:limit].to_i <= Settings.max_changeset_query_limit
434           params[:limit].to_i
435         else
436           raise OSM::APIBadUserInput, "Changeset limit must be between 1 and #{Settings.max_changeset_query_limit}"
437         end
438       else
439         Settings.default_changeset_query_limit
440       end
441     end
442   end
443 end