]> git.openstreetmap.org Git - rails.git/blob - app/controllers/changeset_controller.rb
ca501fd43183cc3d45d09d53b01eb4434064fb70
[rails.git] / app / controllers / changeset_controller.rb
1 # The ChangesetController is the RESTful interface to Changeset objects
2
3 class ChangesetController < ApplicationController
4   layout 'site'
5   require 'xml/libxml'
6
7   before_filter :authorize_web, :only => [:list]
8   before_filter :set_locale, :only => [:list]
9   before_filter :authorize, :only => [:create, :update, :delete, :upload, :include, :close]
10   before_filter :require_allow_write_api, :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, :list]
14   before_filter(:only => [:list]) { |c| c.check_database_readable(true) }
15   after_filter :compress_output
16   around_filter :api_call_handle_error, :except => [:list]
17   around_filter :web_timeout, :only => [:list]
18
19   # Help methods for checking boundary sanity and area size
20   include MapBoundary
21
22   # Helper methods for checking consistency
23   include ConsistencyValidations
24
25   # Create a changeset from XML.
26   def create
27     assert_method :put
28
29     cs = Changeset.from_xml(request.raw_post, true)
30
31     # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
32     cs.user_id = @user.id
33     cs.save_with_tags!
34     render :text => cs.id.to_s, :content_type => "text/plain"
35   end
36
37   ##
38   # Return XML giving the basic info about the changeset. Does not 
39   # return anything about the nodes, ways and relations in the changeset.
40   def read
41     changeset = Changeset.find(params[:id])
42     render :text => changeset.to_xml.to_s, :content_type => "text/xml"
43   end
44   
45   ##
46   # marks a changeset as closed. this may be called multiple times
47   # on the same changeset, so is idempotent.
48   def close 
49     assert_method :put
50     
51     changeset = Changeset.find(params[:id])    
52     check_changeset_consistency(changeset, @user)
53
54     # to close the changeset, we'll just set its closed_at time to
55     # now. this might not be enough if there are concurrency issues, 
56     # but we'll have to wait and see.
57     changeset.set_closed_time_now
58
59     changeset.save!
60     render :nothing => true
61   end
62
63   ##
64   # insert a (set of) points into a changeset bounding box. this can only
65   # increase the size of the bounding box. this is a hint that clients can
66   # set either before uploading a large number of changes, or changes that
67   # the client (but not the server) knows will affect areas further away.
68   def expand_bbox
69     # only allow POST requests, because although this method is
70     # idempotent, there is no "document" to PUT really...
71     assert_method :post
72
73     cs = Changeset.find(params[:id])
74     check_changeset_consistency(cs, @user)
75     
76     # keep an array of lons and lats
77     lon = Array.new
78     lat = Array.new
79     
80     # the request is in pseudo-osm format... this is kind-of an
81     # abuse, maybe should change to some other format?
82     doc = XML::Parser.string(request.raw_post).parse
83     doc.find("//osm/node").each do |n|
84       lon << n['lon'].to_f * GeoRecord::SCALE
85       lat << n['lat'].to_f * GeoRecord::SCALE
86     end
87     
88     # add the existing bounding box to the lon-lat array
89     lon << cs.min_lon unless cs.min_lon.nil?
90     lat << cs.min_lat unless cs.min_lat.nil?
91     lon << cs.max_lon unless cs.max_lon.nil?
92     lat << cs.max_lat unless cs.max_lat.nil?
93     
94     # collapse the arrays to minimum and maximum
95     cs.min_lon, cs.min_lat, cs.max_lon, cs.max_lat = 
96       lon.min, lat.min, lon.max, lat.max
97     
98     # save the larger bounding box and return the changeset, which
99     # will include the bigger bounding box.
100     cs.save!
101     render :text => cs.to_xml.to_s, :content_type => "text/xml"
102   end
103
104   ##
105   # Upload a diff in a single transaction.
106   #
107   # This means that each change within the diff must succeed, i.e: that
108   # each version number mentioned is still current. Otherwise the entire
109   # transaction *must* be rolled back.
110   #
111   # Furthermore, each element in the diff can only reference the current
112   # changeset.
113   #
114   # Returns: a diffResult document, as described in 
115   # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
116   def upload
117     # only allow POST requests, as the upload method is most definitely
118     # not idempotent, as several uploads with placeholder IDs will have
119     # different side-effects.
120     # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
121     assert_method :post
122
123     changeset = Changeset.find(params[:id])
124     check_changeset_consistency(changeset, @user)
125     
126     diff_reader = DiffReader.new(request.raw_post, changeset)
127     Changeset.transaction do
128       result = diff_reader.commit
129       render :text => result.to_s, :content_type => "text/xml"
130     end
131   end
132
133   ##
134   # download the changeset as an osmChange document.
135   #
136   # to make it easier to revert diffs it would be better if the osmChange
137   # format were reversible, i.e: contained both old and new versions of 
138   # modified elements. but it doesn't at the moment...
139   #
140   # this method cannot order the database changes fully (i.e: timestamp and
141   # version number may be too coarse) so the resulting diff may not apply
142   # to a different database. however since changesets are not atomic this 
143   # behaviour cannot be guaranteed anyway and is the result of a design
144   # choice.
145   def download
146     changeset = Changeset.find(params[:id])
147     
148     # get all the elements in the changeset and stick them in a big array.
149     elements = [changeset.old_nodes, 
150                 changeset.old_ways, 
151                 changeset.old_relations].flatten
152     
153     # sort the elements by timestamp and version number, as this is the 
154     # almost sensible ordering available. this would be much nicer if 
155     # global (SVN-style) versioning were used - then that would be 
156     # unambiguous.
157     elements.sort! do |a, b| 
158       if (a.timestamp == b.timestamp)
159         a.version <=> b.version
160       else
161         a.timestamp <=> b.timestamp 
162       end
163     end
164     
165     # create an osmChange document for the output
166     result = OSM::API.new.get_xml_doc
167     result.root.name = "osmChange"
168
169     # generate an output element for each operation. note: we avoid looking
170     # at the history because it is simpler - but it would be more correct to 
171     # check these assertions.
172     elements.each do |elt|
173       result.root <<
174         if (elt.version == 1) 
175           # first version, so it must be newly-created.
176           created = XML::Node.new "create"
177           created << elt.to_xml_node
178         else
179           # get the previous version from the element history
180           prev_elt = elt.class.find([elt.id, elt.version])
181           unless elt.visible
182             # if the element isn't visible then it must have been deleted, so
183             # output the *previous* XML
184             deleted = XML::Node.new "delete"
185             deleted << prev_elt.to_xml_node
186           else
187             # must be a modify, for which we don't need the previous version
188             # yet...
189             modified = XML::Node.new "modify"
190             modified << elt.to_xml_node
191           end
192         end
193     end
194
195     render :text => result.to_s, :content_type => "text/xml"
196   end
197
198   ##
199   # query changesets by bounding box, time, user or open/closed status.
200   def query
201     # create the conditions that the user asked for. some or all of
202     # these may be nil.
203     changesets = Changeset.scoped
204     changesets = conditions_bbox(changesets, params['bbox'])
205     changesets = conditions_user(changesets, params['user'], params['display_name'])
206     changesets = conditions_time(changesets, params['time'])
207     changesets = conditions_open(changesets, params['open'])
208     changesets = conditions_closed(changesets, params['closed'])
209
210     # create the results document
211     results = OSM::API.new.get_xml_doc
212
213     # add all matching changesets to the XML results document
214     changesets.order("created_at DESC").limit(100).each do |cs|
215       results.root << cs.to_xml_node
216     end
217
218     render :text => results.to_s, :content_type => "text/xml"
219   end
220   
221   ##
222   # updates a changeset's tags. none of the changeset's attributes are
223   # user-modifiable, so they will be ignored.
224   #
225   # changesets are not (yet?) versioned, so we don't have to deal with
226   # history tables here. changesets are locked to a single user, however.
227   #
228   # after succesful update, returns the XML of the changeset.
229   def update
230     # request *must* be a PUT.
231     assert_method :put
232
233     changeset = Changeset.find(params[:id])
234     new_changeset = Changeset.from_xml(request.raw_post)
235
236     unless new_changeset.nil?
237       check_changeset_consistency(changeset, @user)
238       changeset.update_from(new_changeset, @user)
239       render :text => changeset.to_xml, :mime_type => "text/xml"
240     else
241       
242       render :nothing => true, :status => :bad_request
243     end
244   end
245
246   
247   
248   ##
249   # list edits (open changesets) in reverse chronological order
250   def list
251     if request.format == :atom and params[:page]
252       redirect_to params.merge({ :page => nil }), :status => :moved_permanently
253     else
254       changesets = conditions_nonempty(Changeset.scoped)
255
256       if params[:display_name]
257         user = User.find_by_display_name(params[:display_name])
258         
259         if user and user.active?
260           if user.data_public? or user == @user
261             changesets = changesets.where(:user_id => user.id)
262           else
263             changesets = changesets.where("false")
264           end
265         elsif request.format == :html
266           @title = t 'user.no_such_user.title'
267           @not_found_user = params[:display_name]
268           render :template => 'user/no_such_user', :status => :not_found
269         end
270       end
271       
272       if params[:bbox]
273         bbox = params[:bbox]
274       elsif params[:minlon] and params[:minlat] and params[:maxlon] and params[:maxlat]
275         bbox = params[:minlon] + ',' + params[:minlat] + ',' + params[:maxlon] + ',' + params[:maxlat]
276       end
277       
278       if bbox
279         changesets = conditions_bbox(changesets, bbox)
280         bbox = BoundingBox.from_s(bbox)
281         bbox_link = render_to_string :partial => "bbox", :object => bbox
282       end
283       
284       if user
285         user_link = render_to_string :partial => "user", :object => user
286       end
287       
288       if user and bbox
289         @title =  t 'changeset.list.title_user_bbox', :user => user.display_name, :bbox => bbox.to_s
290         @heading =  t 'changeset.list.heading_user_bbox', :user => user.display_name, :bbox => bbox.to_s
291         @description = t 'changeset.list.description_user_bbox', :user => user_link, :bbox => bbox_link
292       elsif user
293         @title =  t 'changeset.list.title_user', :user => user.display_name
294         @heading =  t 'changeset.list.heading_user', :user => user.display_name
295         @description = t 'changeset.list.description_user', :user => user_link
296       elsif bbox
297         @title =  t 'changeset.list.title_bbox', :bbox => bbox.to_s
298         @heading =  t 'changeset.list.heading_bbox', :bbox => bbox.to_s
299         @description = t 'changeset.list.description_bbox', :bbox => bbox_link
300       else
301         @title =  t 'changeset.list.title'
302         @heading =  t 'changeset.list.heading'
303         @description = t 'changeset.list.description'
304       end
305
306       @page = (params[:page] || 1).to_i
307       @page_size = 20
308
309       @bbox = bbox
310       
311       @edits = changesets.order("changesets.created_at DESC").offset((@page - 1) * @page_size).limit(@page_size).preload(:user, :changeset_tags)
312     end
313   end
314
315 private
316   #------------------------------------------------------------
317   # utility functions below.
318   #------------------------------------------------------------  
319
320   ##
321   # if a bounding box was specified then parse it and do some sanity 
322   # checks. this is mostly the same as the map call, but without the 
323   # area restriction.
324   def conditions_bbox(changesets, bbox)
325     unless bbox.nil?
326       raise OSM::APIBadUserInput.new("Bounding box should be min_lon,min_lat,max_lon,max_lat") unless bbox.count(',') == 3
327       bbox = sanitise_boundaries(bbox.split(/,/))
328       raise OSM::APIBadUserInput.new("Minimum longitude should be less than maximum.") unless bbox[0] <= bbox[2]
329       raise OSM::APIBadUserInput.new("Minimum latitude should be less than maximum.") unless bbox[1] <= bbox[3]
330       return changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
331                               (bbox[2] * GeoRecord::SCALE).to_i,
332                               (bbox[0] * GeoRecord::SCALE).to_i,
333                               (bbox[3] * GeoRecord::SCALE).to_i,
334                               (bbox[1] * GeoRecord::SCALE).to_i)
335     else
336       return changesets
337     end
338   end
339
340   ##
341   # restrict changesets to those by a particular user
342   def conditions_user(changesets, user, name)
343     unless user.nil? and name.nil?
344       # shouldn't provide both name and UID
345       raise OSM::APIBadUserInput.new("provide either the user ID or display name, but not both") if user and name
346
347       # use either the name or the UID to find the user which we're selecting on.
348       u = if name.nil?
349             # user input checking, we don't have any UIDs < 1
350             raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
351             u = User.find(user.to_i)
352           else
353             u = User.find_by_display_name(name)
354           end
355
356       # make sure we found a user
357       raise OSM::APINotFoundError.new if u.nil?
358
359       # should be able to get changesets of public users only, or 
360       # our own changesets regardless of public-ness.
361       unless u.data_public?
362         # get optional user auth stuff so that users can see their own
363         # changesets if they're non-public
364         setup_user_auth
365         
366         raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
367       end
368       return changesets.where(:user_id => u.id)
369     else
370       return changesets
371     end
372   end
373
374   ##
375   # restrict changes to those closed during a particular time period
376   def conditions_time(changesets, time) 
377     unless time.nil?
378       # if there is a range, i.e: comma separated, then the first is 
379       # low, second is high - same as with bounding boxes.
380       if time.count(',') == 1
381         # check that we actually have 2 elements in the array
382         times = time.split(/,/)
383         raise OSM::APIBadUserInput.new("bad time range") if times.size != 2 
384
385         from, to = times.collect { |t| DateTime.parse(t) }
386         return changesets.where("closed_at >= ? and created_at <= ?", from, to)
387       else
388         # if there is no comma, assume its a lower limit on time
389         return changesets.where("closed_at >= ?", DateTime.parse(time))
390       end
391     else
392       return changesets
393     end
394     # stupid DateTime seems to throw both of these for bad parsing, so
395     # we have to catch both and ensure the correct code path is taken.
396   rescue ArgumentError => ex
397     raise OSM::APIBadUserInput.new(ex.message.to_s)
398   rescue RuntimeError => ex
399     raise OSM::APIBadUserInput.new(ex.message.to_s)
400   end
401
402   ##
403   # return changesets which are open (haven't been closed yet)
404   # we do this by seeing if the 'closed at' time is in the future. Also if we've
405   # hit the maximum number of changes then it counts as no longer open.
406   # if parameter 'open' is nill then open and closed changesets are returned
407   def conditions_open(changesets, open)
408     if open.nil?
409       return changesets
410     else
411       return changesets.where("closed_at >= ? and num_changes <= ?", 
412                               Time.now.getutc, Changeset::MAX_ELEMENTS)
413     end
414   end
415   
416   ##
417   # query changesets which are closed
418   # ('closed at' time has passed or changes limit is hit)
419   def conditions_closed(changesets, closed)
420     if closed.nil?
421       return changesets
422     else
423       return changesets.where("closed_at < ? or num_changes > ?", 
424                               Time.now.getutc, Changeset::MAX_ELEMENTS)
425     end
426   end
427
428   ##
429   # eliminate empty changesets (where the bbox has not been set)
430   # this should be applied to all changeset list displays
431   def conditions_nonempty(changesets)
432     return changesets.where("num_changes > 0")
433   end
434   
435 end