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